erase duplicates and sort a vector
To remove duplicates and sort a vector in C++, you can use the following code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {4, 2, 1, 3, 2, 4, 1};
sort(vec.begin(), vec.end());
vec.erase(unique(vec.begin(), vec.end()), vec.end());
for (int i : vec) {
cout << i << " ";
}
return 0;
}
This code first sorts the vector using the sort
function from the algorithm library. Then, it uses the erase
function in combination with unique
to remove the duplicate elements from the vector. Finally, it prints the elements of the modified vector to the console.