Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL container assignment and const pointers

This compiles:

int* p1;
const int* p2;
p2 = p1;

This does not:

vector<int*> v1;
vector<const int*> v2;
v2 = v1;  // Error!
v2 = static_cast<vector<const int*> >(v1);  // Error!

What are the type equivalence rules for nested const pointers? I thought the conversion would be implicit. Besides, I'd rather not implement point-wise assignment of STL containers, unless I really have to.

like image 216
Lajos Nagy Avatar asked May 23 '09 22:05

Lajos Nagy


2 Answers

Direct assignment is not possible. As others explained, the equivalence is not established by the pointer types, but by the container types. In this case, vector doesn't want to accept another vector that has a different, but compatible element type.

No real problem, since you can use the assign member function:

v2.assign(v1.begin(), v1.end());
like image 181
Johannes Schaub - litb Avatar answered Nov 16 '22 00:11

Johannes Schaub - litb


Conversion from int* to const int* is built into the language, but vectors of these have no automatic conversion from one to the other.

like image 32
Nikolai Fetissov Avatar answered Nov 16 '22 02:11

Nikolai Fetissov