使用映射C ++的输出错误 [英] Wrong output with map C++

查看:237
本文介绍了使用映射C ++的输出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码来构造std :: pair作为unordered_map的键。但是,我不知道为什么我得到所有0作为矢量的输出。有人可以建议我在哪里出错?

I wrote the following code for constructing std::pair as key to unordered_map. However, I dont know why I am getting all 0's as output of vector. Can someone please suggest as to where am I going wrong?

struct key_hash
{
    size_t operator()(const std::pair<unsigned,unsigned>& key) const
    {
        return uint64_t((key.first << 32) | key.second);
    }
};

typedef std::unordered_map<std::pair<unsigned,unsigned>, std::vector<unsigned>, key_hash> MyMap;


int main()
{    
    MyMap m;
    vector<unsigned> t;
    t.push_back(4);
    t.push_back(5);
    m[make_pair(4294967292,4294967291)]=t;

    for(vector<unsigned>::iterator i=m[make_pair(4294967292,4294967291)].begin(),j=m[make_pair(2147483645,2147483643)].end();i!=j;++i)
        cout<<"vec="<<(*i)<<"\n";

    cout<<"vector empty. \n";
}


推荐答案

strong>和 j 是对2个不同向量的迭代器,它们不能进行比较。

i and j are iterators to 2 different vector's and they cannot be compared. Using debug iterators might catch this under visual studio.

这段代码: j = m [make_pair(2147483645,2147483643)]。

This code: j=m[make_pair(2147483645,2147483643)].end(); will create a new empty vector since the key is different from the previously used one.

Whem初始化 j 例如:

Whem initializing j like this: j=m[make_pair(4294967292,4294967291)].end(); the results are fine:


vec = 4
vec = 5
向量为空。

这篇关于使用映射C ++的输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆