Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-place C++ set intersection

Tags:

The standard way of intersecting two sets in C++ is to do the following:

std::set<int> set_1;  // With some elements std::set<int> set_2;  // With some other elements std::set<int> the_intersection;  // Destination of intersect std::set_intersection(set_1.begin(), set_1.end(), set_2.begin(), set_2.end(), std::inserter(the_intersection, the_intersection.end())); 

How would I go about doing an in-place set intersection? That is, I want set_1 to have the results of the call to set_intersection. Obviously, I can just do a set_1.swap(the_intersection), but this is a lot less efficient than intersecting in-place.

like image 706
ChrisInEdmonton Avatar asked Nov 20 '09 22:11

ChrisInEdmonton


People also ask

What is set intersection in C++?

std::set_intersection in C++ The intersection of two sets is formed only by the elements that are present in both sets. The elements copied by the function come always from the first range, in the same order. The elements in the both the ranges shall already be ordered.

How does set intersection work?

Python Set intersection() Method The intersection() method returns a set that contains the similarity between two or more sets. Meaning: The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.

How do you find the intersection of two or more sets in Python?

Python count intersection of sets To count the intersection of sets in Python, we will use “len(set(set1) & set(set2))”. Here, ” & “ is an intersection element common to both. It will return the count as “3” because “10, 8, and 6” are common to both the sets.


1 Answers

I think I've got it:

std::set<int>::iterator it1 = set_1.begin(); std::set<int>::iterator it2 = set_2.begin(); while ( (it1 != set_1.end()) && (it2 != set_2.end()) ) {     if (*it1 < *it2) {         set_1.erase(it1++);     } else if (*it2 < *it1) {         ++it2;     } else { // *it1 == *it2             ++it1;             ++it2;     } } // Anything left in set_1 from here on did not appear in set_2, // so we remove it. set_1.erase(it1, set_1.end()); 

Anyone see any problems? Seems to be O(n) on the size of the two sets. According to cplusplus.com, std::set erase(position) is amortized constant while erase(first,last) is O(log n).

like image 50
ChrisInEdmonton Avatar answered Sep 19 '22 06:09

ChrisInEdmonton