C++/Removing Duplicates in a Vector
Expert: vijayan - 4/6/2011
QuestionI am writing a program that is suppose to remove duplicates in a vector. I am having trouble writing the remove_duplicates function. I am suppose to go through all the elements and check to see if the same value occurs at a lower index. If true, remove the element.
Here is my code so far..
#include <iostream>
#include <vector>
using namespace std;
void remove_element(int pos, vector<int>&a)
{
for(int i = pos; i < a.size() - 1; i++)
{
a[i] = a[i + 1];
a.pop_back();
}
}
void remove_duplicates(vector<int>& a,vector<int>& b)
{
for(int k = 0; k < a.size()-1; k++)
{
if(a[k] == a[k+1])
}
}
void printVector(vector<int> a)
{
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << "\n";
}
int main()
{
vector<int> empty;
vector<int> v1(9);
v1[0] = 1; v1[1] = 4; v1[2] = 9; v1[3] = 16;
v1[4] = 9; v1[5] = 7; v1[6] = 4; v1[7] = 9; v1[8] = 11;
vector<int> v2(7);
v2[0] = 11; v2[1] = 11; v2[2] = 7; v2[3] = 9; v2[4] = 16;
v2[5] = 4; v2[6] = 1;
remove_duplicates(empty);
printVector(empty);
printVector(v1);
remove_duplicates(v1);
printVector(v1);
printVector(v2);
remove_duplicates(v2);
printVector(v2);
}"
Answer> I am suppose to go through all the elements and check to see if the same value occurs at a lower index.
bool value_occurs_at_a_lower_index( std::vector<int>& vec, std::vector<int>::size_type pos )
{
for( std::vector<int>::size_type i = 0 ; i < pos ; ++i )
if( vec[i] == vec[pos] ) return true ;
return false ;
}
> If true, remove the element.
for( std::vector<int>::size_type i = 0 ; i < pos ; )
{
if( value_occurs_at_a_lower_index( vec, i ) vec.erase( vec.begin() + i )
else ++i ;
}