我有一个:map<vector<int>, vector<int>> info
我必须进行搜索。我尝试:
Key[0]=1;
Key[1]=3;
Key[2]=1;
test=info.find(key);
其中Key
和test
定义如下:vector<int> Key (3,0)
和vector<int> test (2,0)
。
但这会返回编译错误:error: no match for 'operator=' in 'test =
. 这是什么原因?
find
返回一个迭代器。首先,您需要通过针对info.end()
. 然后,您需要从存储在该对的第二个中的值进行分配。
auto it = info.find(key);
// pre-c++11: std::map<vector<int>, vector<int> >::iterator it = info.find(key)
if (it != info.end())
{
test = it->second;
}
您收到错误是因为std::vector
没有用于迭代器赋值的运算符重载。
std::vector<int>::find
返回一个输入迭代器。std::vector<int>::operator=
接受另一个std::vector<int>
或 C++11 初始化器列表。
你应该尝试这样的事情。
// Some map.
std::map<std::vector<int>, std::vector<int>> info{ { { 1, 3, 1 }, { 5, 5, 5 } } };
auto itr = info.find({ 1, 3, 1 }); // Find element
if (itr != std::end(info)) { // Only if found
auto& v = itr->second; // Iterator returns std::pair (key, value)
for (auto i : v) { // Print result or do what you want.
std::cout << i << std::endl;
}
}