读书人

该如何用数组删除重复数

发布时间: 2012-02-07 17:45:36 作者: rapoo

该怎么用数组删除重复数
用数组形式来删除一个数组中重复的数字(如:1 5 6 2 3 3 5 。把重复的删除后是:1 5 6 2 3)。用指针形式我就可以完成,但是用数组我怎么都弄不出来。大虾支招!

[解决办法]
for example
int a[] = {1,5,6,2,3,3,5};
int count = 0;
for (int i=0; i <7; i++) {
for (int j=i-1; i> =0; j--) {
if (a[j] == a[i]) {
a[i] = 0;
count++;
break;
}
}
}
int b[7-count];
count = 0;
for (int i=0; i <7; i++) {
if (a[i] != 0) {
b[count++] = a[i];
}
}

仅供参考


[解决办法]
int a[] = {1,5,6,2,3,3,5};
int b[];
map <int,int> count;
for(i = 0;i < sizeof(a)/sizeof(int);i++)
count[a[i]]++;
for(i = 0;i < sizeof(a)/sizeof(int);i++)
if(count[a[i]] == 1)
b[i] = a[i];

[解决办法]
unique_copy
Syntax:
#include <algorithm>
iterator unique_copy( iterator start, iterator end, iterator result );
iterator unique_copy( iterator start, iterator end, iterator result, BinPred p );

The unique_copy() function copies the range [start,end) to result, removing all consecutive duplicate elements. If the binary predicate p is provided, then it is used to test two elements to see if they are duplicates.

The return value of unique_copy() is an iterator to the end of the new range.


[解决办法]
我以前写的:
void genericAlgorithmSort()
{
istream_iterator <int> cin_it(cin);// reads ints from cin
istream_iterator <int> end_of_stream;// end iterator value
// initialize vec from the standard input
vector <int> vec(cin_it, end_of_stream);
sort(vec.begin(), vec.end());
// writes ints to cout using " " as the delimiter
ostream_iterator <int> output(cout, " ");
// write only the unique elements in vec to the standard output
unique_copy(vec.begin(), vec.end(), output);
}

读书人网 >C++

热点推荐