C ++ STL映射我不想让它排序! [英] C++ STL map I don't want it to sort!

查看:139
本文介绍了C ++ STL映射我不想让它排序!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

map<string,int> persons;

persons["B"] = 123;
persons["A"] = 321;


for(map<string,int>::iterator i = persons.begin();
    i!=persons.end();
    ++i)
{
    cout<< (*i).first << ":"<<(*i).second<<endl;
}

预期输出:

  B:123
  A:321

但它的输出是:

  A:321
  B:123

我想让它保持键和值插入 map的顺序

I want it to maintain the order in which keys and values were inserted in the map<string,int>.

有可能吗?还是应该使用一些其他的STL数据结构?哪一个?

Is it possible? Or should I use some other STL data structure? Which one?

推荐答案

没有标准容器直接做你想要的。使用明显的容器,如果你想维护插入顺序是一个向量。如果还需要通过字符串查找,请使用向量和映射。映射通常是字符串到向量的索引,但是因为你的数据已经是整数,你可能只是想复制它,这取决于你的用例。

There is no standard container that does directly what you want. The obvious container to use if you want to maintain insertion order is a vector. If you also need look up by string, use a vector AND a map. The map would in general be of string to vector index, but as your data is already integers you might just want to duplicate it, depending on your use case.

这篇关于C ++ STL映射我不想让它排序!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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