【问题标题】:How to associate each token in a set with a set of tokens in C++如何将集合中的每个标记与 C++ 中的一组标记相关联
【发布时间】:2013-10-03 01:54:40
【问题描述】:

我有一组这样声明的令牌:

std::set<std::string> tokens;

我向其中insert 了一些有序的令牌字符串。现在我需要将集合中的每个标记与另一组唯一的字符串标记相关联。在 C 中,我只保留一个标记数组和一个标记数组,它们将共享相同的第一维索引。我想知道的是这种数据结构的“C++版本”是什么以及它是如何实现的。

tokens = {"list1", "list2"}
sets = {"list1": {"item1", "item2", "item3"}, "list2": {"item1", "item2"}}

这几乎就是我想要的,最终目标是对从标准输入中获取的标记执行集合操作。

【问题讨论】:

  • 你把push_back变成std::set??
  • 糟糕,与向量混淆了。是的,我的意思是插入。

标签: c++ string set token


【解决方案1】:

您可以为此使用std::map。

std::map<std::string, std::set<std::string>> tokens;
tokens["list1"].insert("item1");
tokens["list1"].insert("item2");
tokens["list1"].insert("item3");
tokens["list2"].insert("item1");
tokens["list2"].insert("item2");
// etc

【讨论】:

  • 抱歉回复晚了,我以为我已经接受了你的回答。 std::map 正是我所需要的!
【解决方案2】:

您可能应该使用 std::multimap 而不是集合。 这将保证每个“键”出现一次,并且每个“值”每个键最多出现一次,尽管多个键可能出现相同的值。

【讨论】:

  • 直到今天才回过头来,我只是想指出我发现 std::multimap 允许重复键,而 std::map 强制键的唯一性。
猜你喜欢
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多