STL容器赋值和常量指针

STL容器赋值和常量指针

本文介绍了STL容器赋值和常量指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这会编译:

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

这不会:

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

嵌套常量指针的类型等价规则是什么?我认为转换将是隐含的。除此之外,我不想实现STL容器的点分配,除非我真的需要。

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.

推荐答案

不可能。正如其他人解释的,等价性不是由指针类型确定的,而是由容器类型确定的。在这种情况下,向量不想接受具有不同但兼容的元素类型的另一个向量。

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

这篇关于STL容器赋值和常量指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:16