Farjana Parveen Ayubb Farjana Parveen Ayubb - 3 months ago 18
C++ Question

How to apply the intersect between two list in c++?

I am new to C++ list.

I have a two list

list1
and
list2
I need to get the common element between this list, how can i get this?

Answer

You can use: std::set_intersection for that, provided you first sort the two lists:

Example:

#include <algorithm>
#include <iostream>
#include <list>

int main() {
    std::list<int> list1{2, 5, 7, 8, -3, 7};
    std::list<int> list2{9, 1, 6, 3, 5, 2, 11, 0};

    list1.sort();
    list2.sort();

    std::list<int> out;
    std::set_intersection(list1.begin(), list1.end(), list2.begin(), list2.end(), std::back_inserter(out));

     for(auto k : out)
         std::cout << k << ' ';
}

Output:

2 5