如何将地图作为不可变地图传递?

时间:2019-09-30 10:02:35

标签: 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);

但是只要使用地图的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)

1 个答案:

答案 0 :(得分:3)

如果看一下合适的reference documentation for std::map::find,您会看到它有两个重载,它们的区别在于1.隐式this参数的const限定,以及2.返回类型:

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

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