unordered_multimap - iterating the result of find() yields elements with different value(unordered_multimap - 迭代 find() 的结果会产生具有不同值的元素)
问题描述
C++ 中的多重映射似乎很奇怪,我想知道为什么
The multimap in C++ seems to work really odd, i would like to know why
#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 << '	';
        cout << it->second << endl;
    }
    cout << "all values to a" << endl;
    for(auto it = map.find('a'); it != map.end(); it++) {
        cout << it->first << '	' << 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 错误?
why does the output still contain anything with b as the key when I am explicitly asking for 'a'? Is this a compiler or stl bug?
推荐答案
find 实现后,返回与 multimap 中的键匹配的第一个元素的迭代器(与任何其他 map 一样).您可能正在寻找 equal_range:
find, as implemented, returns an iterator for the first element which matches the key in the multimap (as with any other map). You're likely looking for 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 << '	' << it->second << endl;
}
这篇关于unordered_multimap - 迭代 find() 的结果会产生具有不同值的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:unordered_multimap - 迭代 find() 的结果会产生具有不同值的元素
 
				
         
 
            
        基础教程推荐
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- 用指数格式表示浮点数 1970-01-01
- C++多态 1970-01-01
- 总计将在节日礼物上花多少钱 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 对 STL 容器的安全并行只读访问 2022-10-25
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- C语言数组 1970-01-01
- C语言3个整数的数组 1970-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				