c++ - 如何将 map 作为不可变 map 传递?

标签 c++ visual-c++ maps

我有一个 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/

相关文章:

maps - 将鼠标悬停在集群组上时弹出窗口

javascript - 在自定义世界地图上创建我自己的地址、道路和路线

erlang - 当模式匹配在 Erlang 中映射时,为什么这个变量是未绑定(bind)的?

php - 关于 C++ 的一些错误

c++ - C++11 编译器在代码优化期间是否可以将局部变量转换为右值?

c++ - 如果条件太长并且包括 for 循环

c++ - OpenCV - 二值图像中所有非零像素的位置

c++ - 在 Qt 中调整子部件大小后调整大小

c++ - 查找预分配 vector C++ 的非空索引

c++ - 代码分析说 Inconsistent annotation for 'wWinMain' : this instance has no annotations