I was using set_intersection from the STL in C++, and I was wondering if there was any rule on which set would be used when creating the intersection. Or is the behavior undefined, and potentially implementation dependent.
On linux using g++ (ver. 4.4.6), it seems that it always uses the first set that is passed into the set_difference function, but I’m not sure I can rely on this. As you can see from the example below, there is other data in each set member that is not considered in the operator< function.
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
class myClass {
public:
myClass(int val, int data)
: value(val),
metaData(data) {}
// Only consider the value, not metaData
bool operator<(const myClass &other) const{
return value < other.value;
}
void print() const {
cout << "Value: " << value << " metaData: " << metaData << endl;
}
private:
int value;
int metaData;
};
int main() {
// Create two sets with some data
set<myClass> set1;
set<myClass> set2;
set<myClass> intersect;
// Set1 has 1, 2, 3, 4
set1.insert(myClass(1,-10));
set1.insert(myClass(2,-10));
set1.insert(myClass(3,-10));
set1.insert(myClass(4,-10));
// Set2 has -1, 2, 3
set2.insert(myClass(-1, 10));
set2.insert(myClass(2, 10));
set2.insert(myClass(3, 10));
set_intersection(set1.begin(), set1.end(),
set2.begin(), set2.end(),
inserter(intersect, intersect.begin()));
for_each(intersect.begin(), intersect.end(),
mem_fun_ref(&myClass::print));
}
// The output of this code is
// Value: 2 metaData: -10
// Value: 3 metaData: -10
Assuming you’re asking about
set_intersectionas in the question title, rather thanset_differenceas in the code sample, the C++ standard is explicit:C++03 §25.3.5.3[lib.set.intersection]/5Current standard makes this point even stronger, mostly for the sake of multisets which are now stable with regards to the order of equivalent keys:
C++11 §25.4.5.3[set.intersection]/5As for
set_difference, it simply copies the elements of the first sorted sequence that are not present in the second.