不允许使用矢量<const int>。为什么允许 pair<const int、int>?

vector<const int> is not allowed. Why is pair<const int, int> allowed?

本文关键字:int lt gt const pair 为什么 不允许      更新时间:2023-10-16

可能的重复项:
为什么 stackvector<const int> v; //not allowed

但是为什么pair允许const第一个对象呢?事实上,这就是map对象内部的pair所发生的情况。我错过了什么吗?

如能对这一现象作出详细和直观的解释,将不胜感激。

我认为主要原因是因为std::pair不会重新分配对象,因此它们不必是可分配的。

更新:

实际上,向量是唯一需要可分配对象的容器。这是因为相应地,标准向量必须为其元素具有连续的存储位置。因此,如果没有空间添加更多对象,vector 将不得不将其数据重新分配到另一个地方(从而使用对象的可分配属性)。

> std::pair只需要在尝试分配给它时可以分配它的内容。但是,std::vector始终需要分配才能重新分配。