【问题标题】:Why am i getting an overlad error when using .pushback on vector enclosed by a vector为什么在向量包围的向量中使用 .push_back 时出现重载错误
【发布时间】:2020-06-30 07:28:17
【问题描述】:

我正在尝试创建一个哈希表,其中包含一个由结构组成的向量内的向量。 v[1].push_back(value); 它给了我一个错误:

error C2664: 'void std::vector<node,std::allocator<node>>::push_back(_Ty &&)': cannot convert argument 1 from 'int' to 'const _Ty &'
        with
        [
            _Ty=node
        ]
note: Reason: cannot convert from 'int' to 'const _Ty'
        with
        [
            _Ty=node
        ]
note: No constructor could take the source type, or constructor overload resolution was ambiguous

这是我的代码: 结构节点{ 整数数据;

node() {
    data = 0;
}
};

class hashmap {
public:
vector<vector<struct node>> v;
vector<struct node> n;

hashmap() {
    for (int i = 0; i < 5; i++) {
        v.push_back(n);
    }
}


void insert(int key, int value) {
    int index = Hashfunction(key);
    v[1].push_back(value);

}

int Hashfunction(int key) {
    int index = key % v.size();
    return index;
}



};

【问题讨论】:

  • 将节点的 ctor 更改为:node(int d = 0) { data = d; }。现在,您没有从intnode 结构的转换。
  • @rafix07 事件进一步,node( int d = 0 ) : data { d } {}

标签: c++ hash stl std push-back


【解决方案1】:

始终查看完整的错误消息,现代编译器往往很有帮助。在这种情况下,关键信息是:cannot convert from 'int' to 'const _Ty' with _Ty=node,如果您换出类型模板,则会得到cannot convert from 'int' to 'const node'。这与嵌套向量无关。您会在以下代码中看到相同的错误:

struct node {
    int data;

    node() {
        data = 0;
    }
};

vector<struct node> n;
n.push_back(1);

该错误是因为编译器无法将int 转换为node。解决方法是提供一个构造函数,它采用 int:

struct node {
    int data;

    node()
    : data(0)
    {
    }

    node(int value)
    : data(value)
    {
    }
};

注意使用初始化器而不是分配给构造函数主体中的成员,这样会产生更高效的代码。

理想情况下,采用单个参数的构造函数应标记为explicit,以帮助防止出现歧义等问题:

struct node {
    int data;

    node()
    : data(0)
    {
    }

    explicit node(int value)
    : data(value)
    {
    }
};

请注意,您需要稍微更改您的 push_back 调用以显式创建 node

v[1].push_back(node(value));

或者更高效,更少打字:

v[1].emplace_back(value)

【讨论】:

  • : data { 0 } : data { value } 最好明确指定初始化。
  • @arnes 不,对int没有影响
猜你喜欢
  • 2020-08-20
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 2020-02-07
  • 2016-11-16
  • 2022-12-12
  • 1970-01-01
相关资源
最近更新 更多