How to apply the intersection between two lists in C++?

Farjana Parveen Ayubb

I am new to C++ list.

I have two lists: list1 and list2. I need to get common elements between these lists. How can I get this?

WhiZTiM

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

EDIT:

The above method is likely not going to be optimal, mostly because sorting a std::list isn't nice to the CPU...

For a trade-off of space, the method below will certainly be faster for larger sets of data, because we iterate through each list only once, and all operations done at each iteration doesn't go beyond a O(1) amortized complexity

template<typename T>
std::list<T> intersection_of(const std::list<T>& a, const std::list<T>& b){
    std::list<T> rtn;
    std::unordered_multiset<T> st;
    std::for_each(a.begin(), a.end(), [&st](const T& k){ st.insert(k); });
    std::for_each(b.begin(), b.end(),
        [&st, &rtn](const T& k){
            auto iter = st.find(k);
            if(iter != st.end()){
                rtn.push_back(k);
                st.erase(iter);
            }
        }
    );
    return rtn;
}

I used std::unordered_multiset rather than std::unordered_set because it preserves the occurences of common duplicates in both lists

I ran a dirty benchmark for the two methods on randomly generated 9000 ints, The result was (lower is better):

Average timings for 100 runs:
intersection_of:  8.16 ms
sortAndIntersect: 18.38 ms

Analysis of using the std::set_intersection method:

  • Sorting List 1 of size N is: O(Nlog(N))
  • Sorting List 2 of size M is: O(Mlog(M))
  • Finding the Intersection is: O(M + N)
  • Total: O( Nlog(N) + Mlog(M) + M + N) ...(generalized as logarithmic)

Assuming M and N are equal, we can generalize it as: O(Nlog(N))

But if we use the intersection_of method I posted above:

  • Iterating through List 1 of size N and adding to the set is: O(N) + O(1) = O(N)
  • Iterating through List 2 of size M, checking the multiset, adding to out, removing from List 2 : O(M) + O(1) + O(1) + O(1) = O(M)
  • Total: O(M + N) ...(generalized as linear)

Assuming M and N are equal, we can generalize it as: O(N)

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to fill between x and two functions (intersection)?

分類Dev

Checking whether intersection of two lists is valid, returning intersection itself not necessary

分類Dev

Intersection of two lists maintaining duplicate values in Kotlin

分類Dev

Difference between two lists

分類Dev

Finding the intersection in two lists of tuples regardless of tuple order

分類Dev

Do not apply spacing between paragraphs to lists

分類Dev

Python: How to alternate between two questions to retrieve user inputs for two different lists?

分類Dev

intersection of objects except for one attribute between two arrays

分類Dev

HTML send Values between two Select Lists

分類Dev

Selected combinations between the values of two lists

分類Dev

Maximum value between two lists, and their indexes

分類Dev

Is there a way to apply CSS styles between two siblings?

分類Dev

How to use apply for two pandas column including lists to return index in a list in one column using the element in another column?

分類Dev

How to compare two lists in python

分類Dev

intersection of lists return all within list of lists

分類Dev

How to get dates between two dates in C#

分類Dev

How can I find the nth substring in between two substrings in C?

分類Dev

How to check if between two points in time C#

分類Dev

C# How to get connection between two text files

分類Dev

Intersection of Two LineStrings Geopandas

分類Dev

Intersection of two Counters

分類Dev

Intersection of two arrays in BASH

分類Dev

Optimizing finding matching substring between the two lists by regex in Python

分類Dev

Strange difference in time between add and extend two lists

分類Dev

Python: How to check if two lists are not empty

分類Dev

How to check if contents of two lists is same in python?

分類Dev

How to compare two one hot encoded lists?

分類Dev

"How to unevenly iterate over two lists"

分類Dev

How to compare elements of two input lists?

Related 関連記事

  1. 1

    How to fill between x and two functions (intersection)?

  2. 2

    Checking whether intersection of two lists is valid, returning intersection itself not necessary

  3. 3

    Intersection of two lists maintaining duplicate values in Kotlin

  4. 4

    Difference between two lists

  5. 5

    Finding the intersection in two lists of tuples regardless of tuple order

  6. 6

    Do not apply spacing between paragraphs to lists

  7. 7

    Python: How to alternate between two questions to retrieve user inputs for two different lists?

  8. 8

    intersection of objects except for one attribute between two arrays

  9. 9

    HTML send Values between two Select Lists

  10. 10

    Selected combinations between the values of two lists

  11. 11

    Maximum value between two lists, and their indexes

  12. 12

    Is there a way to apply CSS styles between two siblings?

  13. 13

    How to use apply for two pandas column including lists to return index in a list in one column using the element in another column?

  14. 14

    How to compare two lists in python

  15. 15

    intersection of lists return all within list of lists

  16. 16

    How to get dates between two dates in C#

  17. 17

    How can I find the nth substring in between two substrings in C?

  18. 18

    How to check if between two points in time C#

  19. 19

    C# How to get connection between two text files

  20. 20

    Intersection of Two LineStrings Geopandas

  21. 21

    Intersection of two Counters

  22. 22

    Intersection of two arrays in BASH

  23. 23

    Optimizing finding matching substring between the two lists by regex in Python

  24. 24

    Strange difference in time between add and extend two lists

  25. 25

    Python: How to check if two lists are not empty

  26. 26

    How to check if contents of two lists is same in python?

  27. 27

    How to compare two one hot encoded lists?

  28. 28

    "How to unevenly iterate over two lists"

  29. 29

    How to compare elements of two input lists?

ホットタグ

アーカイブ