使映射键根据插入顺序排序
如果没有额外容器(如向量)的帮助,我是否可以使映射的键排序顺序与插入顺序相同?
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<const char*, int> m;
m["c"] = 2;
m["b"] = 2;
m["a"] = 2;
m["d"] = 2;
for (map<const char*, int>::iterator begin = m.begin(); begin != m.end(); begin++) {
// How can I get the loop sequence same as my insert sequence.
// c, b, a, d
std::cout << begin->first << std::endl;
}
getchar();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
std::map
是根据第三个模板参数Compare
排序的,默认为std::less
键>
。如果你想要插入序列,你可以使用std::list >
。编辑:
正如所指出的,任何顺序 STL 容器都会执行:
vector
、deque
、list
或在这种特殊情况下的事件字符串
。您必须根据每个人的优点做出决定。No.
std::map<Key, Data, Compare, Alloc>
is sorted according to the third template parameterCompare
, which defaults tostd::less<Key>
. If you want insert sequence you can usestd::list<std::pair<Key, Data> >
.Edit:
As was pointed out, any sequential STL container would do:
vector
,deque
,list
, or in this particular case eventstring
. You would have to decide on the merits of each.考虑使用 boost::multi_index 容器而不是 std::map。您可以在容器上放置有序映射索引和无序顺序索引。
Consider using a boost::multi_index container instead of a std::map. You can put both an ordered map index and an unordered sequential index on your container.
不。
std::map
是一个排序的容器;不维护插入顺序。有许多使用第二个容器来维护插入顺序的解决方案也就是说,您应该使用 std::string 作为密钥。使用 const char* 作为映射键是一个坏主意:它几乎不可能通过键来访问或搜索元素,因为只会比较指针,而不是字符串本身。
No. A
std::map
is a sorted container; the insertion order is not maintained. There are a number of solutions using a second container to maintain insertion order in response to another, related question.That said, you should use
std::string
as your key. Using aconst char*
as a map key is A Bad Idea: it makes it near impossible to access or search for an element by its key because only the pointers will be compared, not the strings themselves.