same elements in the vector
Dear all,
I want to establish if certain vector contains certain element and if a vector contains two identical elements.
Is there any fiunctiona vailable that does this stuff or I have to write code myself?
Thank you
[234 byte] By [
lontana] at [2007-11-20 11:50:11]

# 1 Re: same elements in the vector
Dear all,
I want to establish if certain vector contains certain element and if a vector contains two identical elements.
Is there any fiunctiona vailable that does this stuff or I have to write code myself?
Thank you
Hi,
AFAIK the function to find the duplicate items is not there... infact we can do it manually..
Thanx..
# 2 Re: same elements in the vector
You could try something like this
#include <vector>
#include <iostream>
using namespace std;
void check( vector<int> & iv, int v ) {
vector<int>::iterator i;
i = find(iv.begin(), iv.end(), v );
if ( i != iv.end() ) {
++i;
i = find(i, iv.end(), v );
if ( i != iv.end() ) {
cout << "found " << v << " multiple times" << endl;
}
else {
cout << "found " << v << " once" << endl;
}
}
else
cout << v << " not found" << endl;
}
int main() {
vector<int> iv;
iv.push_back(7);
iv.push_back(8);
iv.push_back(7);
check( iv, 7);
check( iv, 8);
check( iv, 0);
}
Kurt
ZuK at 2007-11-11 4:03:41 >

# 3 Re: same elements in the vector
1) you an use std::find to determine if a specific value is in the vector.
2) There are different ways to find if duplicate values exist, but you do
have to do some coding.
a) what do you plan on doing if duplicates exists ? remove them ?
b) Can you modify the existing order of the vector ?
# 4 Re: same elements in the vector
Yes I would like to remove all elements that are the same except one so that the vector does not contains only unique elements.
# 5 Re: same elements in the vector
Don't know if it's the fastest way or not, but the simplest would be to sort the vector and then just check adjacent elements for equality.
# 6 Re: same elements in the vector
1) For general data, I think that Lindley's suggestion is fastest.
sort(v.begin(),v.end());
v.erase( unique(v.begin(),v.end()) , v.end() );
2) You might consider other containers that do not allow
duplicates (such as set).