STL,减少数组,c ++

Cry*_*tal 1 c++ stl

对于hw赋值,我们要编写一个reduce例程,它看起来像:

int reduce(long array[], int size) 
//Where array is the array to reduce, and size is the size of the array.
Run Code Online (Sandbox Code Playgroud)

使用STL.我最初的想法是创建一个集合,将所有项目放在集合中进行比较,但后来我意识到我创建的集合将永远不可用,因为函数返回新集合的大小,但不是集合本身使用.所以我不确定如何使用STL来减少阵列.有什么想法吗?谢谢.

编辑:抱歉,reduce只是将数组减少到一个没有重复的排序数组.

E.g. {4, 4, 2, 1} -> {1, 2, 4}
Run Code Online (Sandbox Code Playgroud)

Ara*_*raK 8

使用std :: sort对数组进行排序,然后在其上应用std :: unique以删除重复项.std :: unique仅适用于已排序的数组.只是为了简化这里的问题是你如何获得beginend本机数组:

long* begin = array;
long* end   = array + size;
Run Code Online (Sandbox Code Playgroud)

一旦掌握了这两项内容,就可以轻松应用标准算法.此外,如果您需要返回新的大小(数组中使用的元素):

long* end_after_unique = unique(...);
return end_after_unique - array;
Run Code Online (Sandbox Code Playgroud)