[英]C++ nested map no matching member function const member
我有一个嵌套的地图,比如
map = {
key : {
innerKey: innerVal
}
}
我正在尝试从标记为const
成员函数中搜索innerVal
。 我正在使用at()
,如此处所述C++ 映射访问丢弃限定符 (const) ,它使我能够映射由key
指向的映射。 但是,当我尝试在嵌套地图上使用at()
时,出现错误:
error: no matching member function for call to 'at'
解决方法:我可以使用迭代器并在嵌套地图上线性搜索,这非常有效。 如何使用at()
或find()
等函数在嵌套地图中进行搜索。
域名注册地址:
private std::map<int, std::map<int, int> > privateStore;
int search(int key1, int key2) const {
return privateStore.at(key1).at(key2); //works when I remove `const` from function signature
}
编辑:它适用于上述简化代码,试试这个,并尝试从第 20 行中删除const
关键字。
#include <iostream>
#include <map>
#include <thread>
template <typename T>
class Foo
{
public:
Foo()
{
std::cout << "init";
}
void set(T val)
{
privateStore[std::this_thread::get_id()][this] = val;
}
T search(std::thread::id key1) const
{
std::map<Foo<T>*, T> retVal = privateStore.at(key1); //works when I remove `const` from function signature
return retVal.at(this);
}
private:
static std::map<std::thread::id, std::map<Foo<T>*, T> > privateStore;
};
template<typename T> std::map<std::thread::id, std::map<Foo<T>*, T> > Foo<T>::privateStore = {};
int main()
{
Foo<int> a;
a.set(12);
std::cout << a.search(std::this_thread::get_id());
}
将内部映射的键声明为指向const
对象的指针。 否则,当您在 const 函数中传递this
时,您将传递Foo<T> const*
而不是Foo<T>*
并且您无法隐式转换它。
所以
static std::map<std::thread::id, std::map<Foo<T> *, T> > privateStore;
到
static std::map<std::thread::id, std::map<Foo<T> const*, T> > privateStore;
和定义相同。
你的例子的活生生的例子 - 固定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.