I'm trying to create a hash table with a vector inside a vector made of a struct. v[1].push_back(value);
it's giving me an error:
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
Here is my code: struct node { int data;
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;
}
};
Always look at the full error message, modern compilers tend to be quite helpful. In this case the key information is: cannot convert from 'int' to 'const _Ty' with _Ty=node
which if you swap out the type template gives cannot convert from 'int' to 'const node'
. This isn't related to having nested vectors. You would see the same error with the following code:
struct node {
int data;
node() {
data = 0;
}
};
vector<struct node> n;
n.push_back(1);
The error is because the compiler has no way to convert from an int
to a node
. The fix is to provide a constructor which takes an int
:
struct node {
int data;
node()
: data(0)
{
}
node(int value)
: data(value)
{
}
};
Note the use of initialisers rather than assigning to the members in the constructor body, this produces more efficient code.
Ideally constructors taking a single argument should be marked explicit
to help prevent issues like ambiguities:
struct node {
int data;
node()
: data(0)
{
}
explicit node(int value)
: data(value)
{
}
};
Note you need to slightly change your push_back
call to explicitly create a node
:
v[1].push_back(node(value));
Or slightly more efficient and less typing:
v[1].emplace_back(value)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.