Let's say I have a set of vector<int>:
std::vector<int> a = {2,3,8,4,9,0,6,10,5,7,1};
std::vector<int> b = {6,10,8,2,4,0};
std::vector<int> c = {0,1,2,4,5,8};
I want to create a new vector, in such a way that only elements which are common to all input vectors are input into the new vector as follows:
std::vector<int> abc = {8,2,0,8}; // possible output, order doesn't matter
I have seen many questions asking for how to remove duplicates, but I wish to retain only duplicates.
Is there an existing efficient STL algorithm or construct that will do this for me, or do I need to write my own?
As mentioned, you can use an algorithm set_intersection  to do this:
But you will also have to sort the vectors first
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
    std::vector<int> a = {0,1,2,3,4,5,6,7,8,9,10};
    std::vector<int> b = {0,2,4,6,8,10};
    std::vector<int> c = {0,1,2,4,5,8};
    std::vector<int> temp;
    std::vector<int> abc;
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());
    std::sort(c.begin(), c.end());
    std::set_intersection(a.begin(), a.end(),
                          b.begin(), b.end(),
                          std::back_inserter(temp));
    std::set_intersection(temp.begin(), temp.end(),
                          c.begin(), c.end(),
                          std::back_inserter(abc));
    for(int n : abc)
        std::cout << n << ' ';
}
LIVE DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With