Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to remove duplicates from vector in C++

3 Answers

0 votes
#include <iostream>
#include <algorithm>
#include <vector>
  
void printVector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}
   
int main ()
{
    std::vector<int> v = { 5, 2, 1, 3, 7, 1, 5, 9, 3, 3, 3 };

    std::sort(v.begin(), v.end()); 
    auto last = std::unique(v.begin(), v.end());
    v.erase(last, v.end()); 
    
    printVector(v);
   
    return 0;
}
   
   
   
   
/*
run:
   
1 2 3 5 7 9 
    
*/

 



answered Apr 12, 2020 by avibootz
0 votes
#include <iostream>
#include <algorithm>
#include <vector>
  
void printVector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}

void removeDuplicates(std::vector<int> &v) {
	auto end = v.end();
	for (auto it = v.begin(); it != end; it++) {
		end = std::remove(it + 1, end, *it);
	}
	v.erase(end, v.end());
}
   
int main ()
{
    std::vector<int> v = { 5, 1, 2, 2, 1, 3, 7, 1, 5, 9, 3, 3, 3 };

    removeDuplicates(v);
    
    printVector(v);
   
    return 0;
}
   
   
   
   
/*
run:
   
5 2 1 3 7 9 
    
*/

 



answered Apr 12, 2020 by avibootz
0 votes
#include <algorithm>
#include <iostream>
#include <vector>
 
int main() {
  std::vector<int> vec = {3, 4, 3, 3, 1, 1, 1, 1, 5, 8};
 
  std::sort(vec.begin(), vec.end());
  
  vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
 
  for (int& n: vec) std::cout << n << " ";

  return 0;
}


/*
run:

1 3 4 5 8 

*/

 



answered Sep 22, 2020 by avibootz
...