STL,减少数组,c++

发布于 2024-09-10 12:58:46 字数 392 浏览 2 评论 0原文

对于硬件分配,我们将编写一个如下所示的reduce 例程:

int reduce(long array[], int size) 
//Where array is the array to reduce, and size is the size of the array.

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

编辑: 抱歉,reduce只是将数组缩减为没有重复的有序数组。

E.g. {4, 4, 2, 1} -> {1, 2, 4}

For a hw assignment, we are to code a reduce routine that looks like:

int reduce(long array[], int size) 
//Where array is the array to reduce, and size is the size of the array.

Using STL. My initial thoughts were to create a set, put all items in the set with a comparison, but then I realized that the set I would create would never be usable since the function returns the size of the new set, but not the set itself to be used. So I'm not sure how I'd go about using the STL to reduce an array. Any thoughts? Thanks.

Edited:
Sorry, reduce is just to reduce the array into a sorted array without duplicates.

E.g. {4, 4, 2, 1} -> {1, 2, 4}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不语却知心 2024-09-17 12:58:46

使用 std::sort 对数组进行排序,然后对其应用 std::unique 以删除重复项。 std::unique 仅适用于排序数组。为了简化问题,这里介绍了如何获取本机数组的 beginend

long* begin = array;
long* end   = array + size;

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

long* end_after_unique = unique(...);
return end_after_unique - array;

Sort the array using std::sort, then apply std::unique on it to remove duplicates. std::unique works only on sorted arrays. Just to simplify matters here is how you get begin and end of a native array:

long* begin = array;
long* end   = array + size;

Once you have these two things, you can apply standard algorithms easily. Also, if you need to return the new size(used elements in the array):

long* end_after_unique = unique(...);
return end_after_unique - array;
葬﹪忆之殇 2024-09-17 12:58:46

std::map 只允许单个条目,并会自动为您对项目进行排序。您的情况中的“第二个”值是“不关心”。

std::map<INT32,INT32> mymap;
mymap[i] = array[i];//inserts if not already present

std::map only allow a single entry and will sort the items for you automatically. The "second" value in your case is a don't care.

std::map<INT32,INT32> mymap;
mymap[i] = array[i];//inserts if not already present
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文