STL container assignment and const pointers

前端 未结 8 1744
时光取名叫无心
时光取名叫无心 2020-12-29 11:52

This compiles:

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

This does not:

vector v1;
vector v2;
v2 = v1;         


        
8条回答
  •  时光说笑
    2020-12-29 12:34

    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());
    

提交回复
热议问题