Reputation:
I am trying to create a program to retain only unique elements in a vector
for example:
vector<string> i = "one", "one", "two".
the output would be:
vector<string> i = "one", "two"
**** This is an implementation of the answer as a function. I get the error vector iterator incompatible when I run it with a sample vector.
void simplifyVector(vector<string> i){
/*vector<string>*/;
sort(i.begin(), i.end());
auto iter = unique(i.begin(), i.end());
while (iter != i.end())
{
i.erase(iter);
}
for (const auto &s : i)
{
cout << s << " ";
}
cout << endl;
}
Upvotes: 0
Views: 5588
Reputation: 167
Use sort and unique. Use sort to but all duplicate values adjacent to each other than unique puts all vales that are adjacent to each other at the end and returns an iterator pointing to the first duplicate element. Then we use a while loop to remove those elements. Remember generic algorithms never delete elements in a container.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
std::vector<std::string> i = {"one", "one", "two"};
std::sort(i.begin(), i.end());
auto iter = std::unique(i.begin(), i.end());
erase(iter, i.end());
for (const auto &s : i)
{
std::cout << s << " ";
}
std::cout << std::endl;
return 0;
}
Upvotes: 1