c++ - 如何将地图作为不可变地图传递?
问题描述
我有一个map
定义如下:
typedef std::map<AsnIdentifier, AsnValue, AsnComparator> MibMap;
我有一个这样的映射,我想将它传递给另一个函数,这样传递给它的函数就不能修改它。
void someFunc() {
MibMap someMap = GetMibMap();
otherFunc(someMap);
}
并且对于不变性的签名otherFunc
可能如下:
void otherFunc(const MibMap& someMap);
但是一旦使用find
地图的功能,我就会得到一个非常详细的编译错误。
void otherFunc(const MibMap& someMap) {
MibMap::iterator findVal = someMap.find(//pass the key to find); //this does not compile
}
一旦我const
从方法签名中删除,编译错误就会消失。原因是什么?我想保持地图不可修改,但同时我不确定这个编译错误。
编辑:编译错误是这样的:
no suitable user-defined conversion from "std::_Tree_const_iterator... (and a whole long list)
解决方案
如果您查看适用于 的参考文档std::map::find
,您会看到它有两个重载,它们的不同之处在于 1. 隐式this
参数的 const 限定,以及 2. 返回类型:
iterator find( const Key& key );
const_iterator find( const Key& key ) const;
从这里开始,您的问题应该很明显:您正在调用const
-qualified find
,但您正在尝试将其结果转换为MibMap::iterator
. 将类型更改findVal
为const_iterator
(或仅使用auto
),它将起作用。
推荐阅读
- windows - 网络资源不可用或进入备用路径
- ios - 如何在使用 xcode 开发 ios 应用程序时读取 csv 文件
- angular - Froala 编辑器 CSS 不应用角度 5
- java - 在 Java 中为 Test Rail 创建 Post Api
- c# - 单元测试基于 Prism 的 WPF 应用程序
- spring-boot - ClassNotFoundException:运行 JUnit5 时的 org.junit.platform.launcher.TestExecutionListener
- ruby-on-rails - CanCanCan 拒绝为 :create 加载集合
- python - python脚本中的变量正在发生变化,但是当我导入变量时,每次都是一样的
- vba - ws.Range(x).value 作为双精度类型不匹配
- sql-server - 如何在 sql-server 查询中查找操作员扫描的页数?