unordered_multimap-迭代find()的结果会产生具有不同值的元素

unordered_multimap - iterating the result of find() yields elements with different value

本文关键字:元素 结果 迭代 multimap- find unordered      更新时间:2023-10-16

C++中的多映射似乎很奇怪,我想知道为什么

#include <iostream>
#include <unordered_map>
using namespace std;
typedef unordered_multimap<char,int> MyMap;
int main(int argc, char **argv)
{
    MyMap map;
    map.insert(MyMap::value_type('a', 1));
    map.insert(MyMap::value_type('b', 2));
    map.insert(MyMap::value_type('c', 3));
    map.insert(MyMap::value_type('d', 4));
    map.insert(MyMap::value_type('a', 7));
    map.insert(MyMap::value_type('b', 18));
    for(auto it = map.begin(); it != map.end(); it++) {
        cout << it->first << 't';
        cout << it->second << endl;
    }
    cout << "all values to a" << endl;
    for(auto it = map.find('a'); it != map.end(); it++) {
        cout << it->first << 't' << it->second << endl;
    }
}

这是输出:

c   3
d   4
a   1
a   7
b   2
b   18
all values to a
a   1
a   7
b   2
b   18

当我明确要求"a"时,为什么输出中仍然包含以b为键的内容?这是编译器错误还是stl错误?

find在实现时,为与多映射中的键匹配的第一个元素返回迭代器(与任何其他映射一样)。您可能正在寻找equal_range:

// Finds a range containing all elements whose key is k.
// pair<iterator, iterator> equal_range(const key_type& k)
auto its = map.equal_range('a');
for (auto it = its.first; it != its.second; ++it) {
    cout << it->first << 't' << it->second << endl;
}

这不是一个bug,而是设计出来的。find向其中一个匹配元素返回迭代器,仅此而已。您将使用您的构造迭代到映射的末尾。

你需要使用multimap::equal_range来做你想要做的事情。

www.cplusplus.com中有一个例子,关于如何使用equal_range方法来获取具有相同键的所有元素。

// unordered_multimap::equal_range
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
typedef std::unordered_multimap<std::string,std::string> stringmap;
int main ()
{
  stringmap myumm = {
     {"orange","FL"},
     {"strawberry","LA"},
     {"strawberry","OK"},
     {"pumpkin","NH"}
  };
  std::cout << "Entries with strawberry:";
  auto range = myumm.equal_range("strawberry");
  for_each (
    range.first,
    range.second,
    [](stringmap::value_type& x){std::cout << " " << x.second;}
  );
  return 0;
}

请参考链接:http://www.cplusplus.com/reference/unordered_map/unordered_multimap/equal_range/

似乎您将迭代器放入对的完整"列表"中,从第一对开始,以"a"作为键。因此,当你迭代到最后时,自然你也会得到"a"之外的一切。如果你寻找"c",你可能会在整个"列表"中重复你在那里做的事情。如果你想要所有的a,也许你应该迭代到"it!=map.end()&it->first=='a'"。