Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用std::set并保留输入顺序_C++_C++11 - Fatal编程技术网

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

C++ 使用std::set并保留输入顺序,c++,c++11,C++,C++11,我希望使用std::set来存储必须唯一的整数,但我不希望对它们进行排序(例如,我需要保留集合的输入顺序) 例如: set<int> exampleSet; exampleSet.insert(5); exampleSet.insert(2); exampleSet.insert(10); exampleSet.insert(0); 我希望它是在原来的顺序,所以 {5,2,10,0} 如何实现这一点?您需要一个有序的集合--您可以找到一个。这或多或少是对std::set的一种“插

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

例如:

set<int> exampleSet;
exampleSet.insert(5);
exampleSet.insert(2);
exampleSet.insert(10);
exampleSet.insert(0);
我希望它是在原来的顺序,所以

{5,2,10,0}

如何实现这一点?

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

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

// 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"));

如果您可能有许多唯一的数字,
std::unordered_集
可能比
std::set
具有更好的性能。该集需要排序顺序才能正常工作。您需要在集合中使用类似于
std::vector
的内容,以避免向其中添加重复元素。您希望对集合执行哪些操作?例如,是否需要删除某些元素?为什么需要知道插入顺序?您打算多久在程序中使用一次插入顺序?一旦偶尔很多次?如果您希望将某种类型的信息绑定到插入的项,那么可能比简单的
int
更健壮的东西会更好?可能是一个
std::set
,它有
int
和插入号?我试过了,但它有错误、理智、简单,没有外部移动部件。。。。
// 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