STL,减少数组,c++
对于硬件分配,我们将编写一个如下所示的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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 std::sort 对数组进行排序,然后对其应用 std::unique 以删除重复项。 std::unique 仅适用于排序数组。为了简化问题,这里介绍了如何获取本机数组的
begin
和end
:一旦掌握了这两件事,您就可以轻松应用标准算法。另外,如果您需要返回新的大小(数组中使用的元素):
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
andend
of a native array: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):
std::map 只允许单个条目,并会自动为您对项目进行排序。您的情况中的“第二个”值是“不关心”。
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.