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,895 questions

51,826 answers

573 users

How to remove the common elements from two vectors in C++

1 Answer

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

int main() {

    std::vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7, 10 };
    std::vector<int> v2 = { 1, 4, 6, 8, 9 };
  
    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());

    std::vector<int> inter;
    std::set_intersection(v1.begin(), v1.end(),
                 v2.begin(), v2.end(),
                 back_inserter(inter));

    v1.erase(set_difference(v1.begin(), v1.end(),
                        inter.begin(), inter.end(),
                        v1.begin()), v1.end());
    std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));

    v2.erase(set_difference(v2.begin(), v2.end(),
                        inter.begin(), inter.end(),
                        v2.begin()), v2.end());

    std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, " "));
}



/*
run:

2 3 5 7 10 8 9 

*/

 



answered Dec 2, 2024 by avibootz
...