c++ - C++ 如何转换 std::vector到 const std::vector?
问题描述
我想投一个std::vector<int>
to const std::vector<const int>
,好像不能自动投。所以我有一些问题:
我可以很容易地
std::vector<int>
转换为const std::vector<int>
,这是为什么呢?如果我想投到
const std::vecor<cosnt int>
,我应该怎么做?我试过 const_cast 但不起作用
解决方案
如果我想投到
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::vector
、std::list
、std::map
等)禁止const
在其模板参数列表中使用成员:因为制作容器本身const
也会制作其内容const
,这是这些容器设计的明确约定。一些“容器”没有这个属性,比如智能指针,这就是为什么你有时会看到这样的东西:
std::shared_ptr<int> ptr = std::make_shared<int>(42);
std::shared_ptr<const int> non_modifying_ptr = ptr;
这是引用计数指针核心功能的一部分。
顺便说一句,这是确保您的代码“常量正确”的全部内容,我强烈建议您对该主题进行谷歌搜索并了解它是什么,以及如何在您的代码中正确应用它来制作您的代码更安全、更高效。
推荐阅读
- r - 折叠一个数据框列表并与 R 中的另一个数据框列表组合
- vba - 在 MS Access 中禁用过滤/未过滤和切换过滤器按钮
- jmeter - JMeter 可以在使用 Blazor 框架开发的应用程序上记录请求吗?
- sql - 使用oracle sql中的窗口函数检查分区中是否存在值
- nlp - 如何为 LayoutLM 准备自定义训练数据
- python - 使用 setuptools 的 python 替代包设置
- statistics - 如何在 Grafana 中按月创建平均值直方图?
- c# - 如何读取和查找 txt 文件中的特定信息并将其与字符串统一进行比较
- python - 在 Python Pandas 中读取带有印地语数据的 Excel
- python - MacOS 上的 pyqt5 默认本机菜单文本