删除重复的数组,而preserving顺序C ++ [英] Removing duplicates in an array while preserving the order in C++

查看:134
本文介绍了删除重复的数组,而preserving顺序C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/1453333/how-to-make-elements-of-vector-unique-remove-non-adjacent-duplicates">How使矢量元素独特之处? (除去非相邻重复)

有其设置为STL算法,可以从阵列中删除重复项,同时preserving订单部分的任何标准算法。举例来说,如果我有这样一个数组 INT一个[] = {2,1,3,1,4,2}; 去除重复它应该是在 A [] = {2,1,3,4}; 。我不能使用的std ::独特作为数组排序。其他的解决方案,如将其插入的std ::设为我失去的元素将得到排序的顺序。有算法,我可以使用或我要code我自己的任何其他组合?

Is there any standard algorithm which is provided as part of STL algorithms which can remove duplicates from an array while preserving the order. For example, if I have an array like int a[] = {2,1,3,1,4,2}; after the removal of duplicates it should be a[] = {2,1,3,4};. I can not use std::unique as the array is not sorted. Other solutions like inserting it into an std::set I lose the order as the elements will get sorted. Is there any other combination of algorithms I can use or do I have to code my own?

推荐答案

没有标准算法,这一点,但它很容易实现。其原理是保持的std ::设为您已经看到,到目前为止,并跳过重复,同时复制到一个新的向量或数组中的项目。这个工作在为O(n LG电子n)时间及O(n)的内存。如果你使用的C ++ 0x,你可以把它降到O(n)的时间用的std :: unordered_set 的看到,项目设置;这款采用二叉树的哈希表来代替,而应该快了。

There is no standard algorithm for this, but it's fairly easy to implement. The principle is to keep a std::set of the items you've seen so far, and skip duplicates while copying to a new vector or array. This operates in O(n lg n) time and O(n) memory. If you're using C++0x, you can get it down to O(n) time by using std::unordered_set for the seen-items set; this uses a hash table instead of binary trees and should be faster.

这篇关于删除重复的数组,而preserving顺序C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆