我想从我的(动态分配的)数组中提取唯一值。我有这样的东西:
[0] 0 int
[1] 1 int
[2] 2 int
[3] 2 int
[4] 2 int
[5] 5 int
[6] 6 int
[7] 6 int
[8] 8 int
[9] 9 int
[10] 10 int
[11] 8 int
[12] 12 int
[13] 10 int
[14] 14 int
[15] 6 int
[16] 2 int
[17] 17 int
[18] 10 int
[19] 5 int
[20] 5 int
我想要一个大小为 12 的数组,其中的每条记录都是来自另一个数组的唯一值。
我该怎么做?
编辑
我忘了说我不能使用 STL 容器(比如 std::vector
或 std::list
)
最佳答案
使用std::unique在使用您最喜欢的排序算法(例如 std::sort)对数组进行排序之后
编辑:
如果没有 STL,最简单的解决方案是在数组中找到最小值和最大值并动态分配一个 bool
数组。遍历数组,如果看到该元素,则将相应的 bool
元素设置为 true
。分配一个包含唯一元素总数的新 int
数组,并用 bool
数组中的数据填充它。
推荐: 对数组进行排序并删除连续的元素。实现快速排序并不难,如果您处理的是整数,radix sort可能会更好。
关于c++ - 如何有效地从数组中提取唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9177423/