映射与矢量作为关键操作查找

时间:2013-11-05 13:13:51

标签: c++ map find

我有一个:map<vector<int>, vector<int>> info

我必须进行搜索。 我试试:

Key[0]=1;
Key[1]=3;
Key[2]=1;
test=info.find(key);

Keytest定义如下:vector<int> Key (3,0)vector<int> test (2,0)

但是这会返回编译错误:error: no match for 'operator=' in 'test =。这是什么原因?

2 个答案:

答案 0 :(得分:4)

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;
}

答案 1 :(得分:0)

您收到错误,因为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;
    }
}