【发布时间】:2016-10-01 21:28:54
【问题描述】:
我有一个嵌套地图,类似于
map = {
key : {
innerKey: innerVal
}
}
我正在尝试从标记为const 的成员函数中搜索innerVal。我正在使用at(),如此处所述C++ map access discards qualifiers (const)
这让我可以找到key 指向的地图。但是,当我尝试在嵌套地图上使用 at() 时,出现错误:
error: no matching member function for call to 'at'
解决方法:我可以使用迭代器并在嵌套地图上进行线性搜索,效果很好。如何使用at()或find()等函数在嵌套地图中进行搜索。
TLDR:
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
}
编辑:它适用于上述简化代码try this,并尝试从第 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());
}
【问题讨论】:
-
它应该可以工作并且works for me。也许将您的代码+错误粘贴到问题中。
-
你是在问搜索的调用吗?
-
给我一些时间来减少问题,无法粘贴确切的代码。
-
@AnuragPeshne 你或许应该在发布之前投入这段时间!