我有一个 map
定义如下:
typedef std::map<AsnIdentifier, AsnValue, AsnComparator> MibMap;
我有一个这样的映射,我想将它传递给另一个函数,这样传递给它的函数就不能修改它。
void someFunc() {
MibMap someMap = GetMibMap();
otherFunc(someMap);
}
为了不变性,otherFunc
的签名可以如下所示:
void otherFunc(const MibMap& someMap);
但是一旦使用 map 的find
函数,我就会得到一个非常详细的编译错误。
void otherFunc(const MibMap& someMap) {
MibMap::iterator findVal = someMap.find(//pass the key to find); //this does not compile
}
只要我从方法签名中删除 const
,编译错误就会消失。这是什么原因呢?我想保持 map 不可修改,但同时我不确定这个编译错误。
编辑:编译错误如下:
no suitable user-defined conversion from "std::_Tree_const_iterator... (and a whole long list)
最佳答案
如果你看看合适的reference documentation for std::map::find
,您会看到它有两个不同的重载:1. 隐式 this
参数的常量限定,以及 2. 返回类型:
iterator find( const Key& key );
const_iterator find( const Key& key ) const;
从这里开始,您的问题应该很明显:您正在调用 const
限定的 find
,但您正试图将其结果转换为 MibMap::迭代器
。将 findVal
的类型更改为 const_iterator
(或者只使用 auto
),它将起作用。
关于c++ - 如何将 map 作为不可变 map 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58165585/