How to remove duplicates from int array in C++

3 Answers

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

void removeDuplicatesFromArray(std::vector<int> &vec) {
    auto it = vec.begin();
 
    while (it != vec.end()) {
        it = adjacent_find(vec.begin(),vec.end());
        if (it != vec.end()) 
            vec.erase(it);
    }
}
 
int main() {
    std::vector<int> vec = {1, 1, 2, 3, 3, 4, 4, 5, 6, 6};
 
    removeDuplicatesFromArray(vec);
     
    for_each (vec.begin(), vec.end(), [](const int elem) {
        std::cout << elem << ' ';
    });
}


 
/*
run:
 
1 2 3 4 5 6 
 
*/

 



answered Feb 11, 2019 by avibootz
edited Feb 9, 2024 by avibootz
0 votes
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

void removeDuplicatesFromArray(std::vector<int> &vec) {
    vec.erase(unique(begin(vec), end(vec)), end(vec));
}
 
int main() {
    std::vector<int> vec = {1, 1, 2, 3, 3, 3, 4, 4, 5, 6, 6};
 
    removeDuplicatesFromArray(vec);
     
    for (auto const& v : vec) std::cout << v << " ";
}



 
/*
run:
 
1 2 3 4 5 6 
 
*/

 



answered Feb 11, 2019 by avibootz
edited Feb 9, 2024 by avibootz
0 votes
#include <set>
#include <iostream>
 
int main() {
    typedef std::set<int> st;
    int arr[] = {3, 4, 3, 3, 1, 1, 1, 1, 5, 8};
  
    st unique_set(arr, arr + sizeof(arr)/sizeof(arr[0]));
  
    for (st::iterator it = unique_set.begin(); it != unique_set.end(); it++)
          std::cout << *it << " ";
}
 
 
 
/*
run:
 
1 3 4 5 8 
 
*/

 



answered Feb 9, 2024 by avibootz

Related questions

3 answers 294 views
294 views asked Feb 12, 2019 by avibootz
1 answer 207 views
1 answer 160 views
2 answers 288 views
1 answer 188 views
1 answer 86 views
...