我有一個嵌套的地圖,像C++嵌套地圖沒有匹配的成員函數const成員
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
#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());
}
它應該工作[適用於我](http://melpon.org/wandbox/permlink/cAVXxUYOKBVoYmjX)。也許將你的代碼+錯誤粘貼到問題中。 – krzaq
[對我也適用](http://cpp.sh/2lelj) – CoryKramer
您是否在詢問關於搜索的調用? –