为什么在向量包含的向量上使用 .push_back 时会出现过载错误

Why am i getting an overlad error when using .pushback on vector enclosed by a vector

我正在尝试创建一个散列 table,其中一个向量位于由结构组成的向量中。 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;
}



};

始终查看完整的错误消息,现代编译器往往很有帮助。在这种情况下,关键信息是: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)