?,c++"/>

首页 > 解决方案 > C++ 如何转换 std::vector到 const std::vector?

问题描述

我想投一个std::vector<int>to const std::vector<const int>,好像不能自动投。所以我有一些问题:

  1. 我可以很容易地std::vector<int>转换为const std::vector<int>,这是为什么呢?

  2. 如果我想投到const std::vecor<cosnt int>,我应该怎么做?我试过 const_cast 但不起作用

标签: c++

解决方案


如果我想投到const std::vecor<cosnt int>,我应该怎么做?我试过const_cast但不起作用

简短的回答:不要。

当您创建一个std::vector<int>const, as-inconst std::vector<int>时,内容本身也会隐含地变为const。换句话说,如果你写这样的东西,你将无法修改元素:

const std::vector<int> values{1,2,3,4,5};

//Nope
//values.emplace_back(6);

//Also Nope
//values[3] = 5;

//Still nope
//values.erase(values.begin() + 1, values.begin() + 3);

//Nuh-uh
//std::vector<int> & mutable_values = values;

//This, however, is okay.
std::vector<int> const& immutable_values = values;

//Same restrictions though
//immutable_values[2] = 6;
//immutable_values.emplace_back(7);

//This is fine
std::vector<int> copy_of_values = values;

//But that's because you made a copy
copy_of_values.emplace_back(6);
assert(copy_of_values.size() != values.size());
assert(copy_of_values != values);

这就是为什么 STL 容器(如std::vectorstd::liststd::map等)禁止const在其模板参数列表中使用成员:因为制作容器本身const也会制作其内容const,这是这些容器设计的明确约定。一些“容器”没有这个属性,比如智能指针,这就是为什么你有时会看到这样的东西:

std::shared_ptr<int> ptr = std::make_shared<int>(42);
std::shared_ptr<const int> non_modifying_ptr = ptr;

这是引用计数指针核心功能的一部分。

顺便说一句,这是确保您的代码“常量正确”的全部内容,我强烈建议您对该主题进行谷歌搜索并了解它是什么,以及如何在您的代码中正确应用它来制作您的代码更安全、更高效。


推荐阅读