微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 std::set 并保留输入顺序

如何解决使用 std::set 并保留输入顺序

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

例如:

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

该集合现在将包含

{0,2,5,10}

我希望它按原来的顺序排列

{5,10,0}

我如何实现这一目标?

解决方法

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

// 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,5,2,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 具有更好的性能。

,

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。