【问题标题】:Use std::set with input order preserved使用 std::set 并保留输入顺序
【发布时间】:2021-04-15 17:57:13
【问题描述】:

我很想使用 std::set 来存储必须唯一的整数,但我不希望它们被排序(例如,我需要保留集合的输入顺序)

例如:

set<int> exampleSet;
exampleSet.insert(5);
exampleSet.insert(2);
exampleSet.insert(10);
exampleSet.insert(0);

该集合现在将包含

{0,2,5,10}

我希望它是原始顺序所以

{5,2,10,0}

我如何做到这一点?

【问题讨论】:

  • 集合需要排序顺序才能正常工作。您需要使用std::vector 之类的内容以及一个集合以避免向其中添加重复元素。
  • 你想在片场做什么操作?例如,您是否需要删除某些元素?
  • 为什么需要知道插入顺序?您打算多久在程序中使用一次插入顺序?一次?不定期的?很多次?如果您想要某种与插入项目相关的信息,也许比简单的int 更强大的东西会更好?可能是一个std::set&lt;std::pair&lt;int, int&gt;&gt;,其中包含int 和插入编号?

标签: c++ c++11


【解决方案1】:

可能最简单和最明显的方法是将集合与向量结合使用:

// We'll use this solely to keep track of whether we've already seen a number
std::set<int> seen;

// and this to store numbers that weren't repeats in order
std::vector<int> result;

// some inputs to work with
std::vector<int> inputs{ 1, 10, 1, 19, 10, 5, 2, 1, 19, 5, 1};

for (int i : inputs)
    if (seen.insert(i).second) // check if it's a duplicate
        result.push_back(i);   // if not, save it

// show the results:
std::copy(result.begin(), result.end(), std::ostream_iterator<int>(std::cout, "\t"));

结果:

1   10  19  5   2

如果您可能有很多唯一编号,std::unordered_set 可能比std::set 具有更好的性能。

【讨论】:

    【解决方案2】:

    你需要一个有序集合——你可以找到一个here。这或多或少是对维护插入顺序的 std::set 的“直接”替代。

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      相关资源
      最近更新 更多