问题描述
没有额外容器(如向量)的帮助,我是否可以使映射的键与插入序列的排序顺序相同?
Without help from additional container (like vector), is it possible that I can make map's key sorted same sequence as insertion sequence?
#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();
}
推荐答案
没有.std::map
是一个已排序的容器;不维护插入顺序.有许多解决方案使用第二个容器来维护插入顺序 回答另一个相关问题.
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.
也就是说,您应该使用 std::string
作为您的密钥.使用 const char*
作为映射键是一个坏主意:它几乎不可能通过键访问或搜索元素,因为只会比较指针,而不是字符串本身.
That said, you should use std::string
as your key. Using a const 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.
这篇关于使映射键根据插入顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!