加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – unordered_multimap – 迭代find()的结果生成具有不同值的

发布时间:2020-12-16 05:37:31 所属栏目:百科 来源:网络整理
导读:C中的multimap似乎很奇怪,我想知道为什么 #include iostream#include unordered_mapusing namespace std;typedef unordered_multimapchar,int MyMap;int main(int argc,char **argv){ MyMap map; map.insert(MyMap::value_type('a',1)); map.insert(MyMap::v
C中的multimap似乎很奇怪,我想知道为什么
#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 bug?

解决方法

如实现的那样,找到与multimap中的键匹配的第一个元素的迭代器(与任何其他映射一样).你可能在寻找 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读