使映射键根据插入顺序排序

发布于 2024-08-29 17:03:42 字数 509 浏览 3 评论 0 原文

如果没有额外容器(如向量)的帮助,我是否可以使映射的键排序顺序与插入顺序相同?

#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();
}

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();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

涙—继续流 2024-09-05 17:03:43

std::map 是根据第三个模板参数Compare排序的,默认为std::less键>。如果你想要插入序列,你可以使用 std::list >

编辑:

正如所指出的,任何顺序 STL 容器都会执行:vectordequelist 或在这种特殊情况下的事件 字符串。您必须根据每个人的优点做出决定。

No. std::map<Key, Data, Compare, Alloc> is sorted according to the third template parameter Compare, which defaults to std::less<Key>. If you want insert sequence you can use std::list<std::pair<Key, Data> >.

Edit:

As was pointed out, any sequential STL container would do: vector, deque, list, or in this particular case event string. You would have to decide on the merits of each.

花落人断肠 2024-09-05 17:03:43

考虑使用 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.

清欢 2024-09-05 17:03:42

不。 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文