首页 > 解决方案 > 如何将地图作为不可变地图传递?

问题描述

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

标签: c++visual-c++maps

解决方案


如果您查看适用于 的参考文档std::map::find,您会看到它有两个重载,它们的不同之处在于 1. 隐式this参数的 const 限定,以及 2. 返回类型:

iterator find( const Key& key );
const_iterator find( const Key& key ) const;

从这里开始,您的问题应该很明显:您正在调用const-qualified find,但您正在尝试将其结果转换为MibMap::iterator. 将类型更改findValconst_iterator(或仅使用auto),它将起作用。


推荐阅读