How to make a vector unique in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm> 
#include <vector>

void printVector(std::vector<int> const &vec) {
    for (auto const &n: vec) {
        std::cout << n << " ";
    }
}
   
int main()
{
    std::vector<int> vec {4, 1, 2, 1, 4, 0, 2, 2, 3, 7, 8, 0, 1, 0, 0};
    
    sort(vec.begin(), vec.end());
    vec.erase(unique(vec.begin(), vec.end()), vec.end());
    
    printVector(vec);
}



/*
run:
   
0 1 2 3 4 7 8 
            
*/

 



answered Feb 21, 2022 by avibootz
edited Oct 23, 2024 by avibootz
...