In the previous posts, I introduced cpplinq, a C++ template library that provides .NET-like query operators for sequences of objects in C++11. In this third installment, I will discuss the set operators the library provides.
There are four set operators: distinct
, union_with
(called so because union
is a keyword in C++), intersect_with
(suffix _with
is for consistency with the union
operator) and except
. These operators should be pretty straight forward: distinct
eliminates the duplicate elements from a sequence, yielding a new sequence with only the distinct elements (in the order their original order), union_with
produces the set union of two sequences, intersect_with
produces the set intersection of two sequences and except
produces the set difference of two sequences.
Before seeing some examples, it worth nothing that all these operators delay the traversal of the sequences until the resulting object is enumerated.
Let’s see some examples:
int numbers[] = {5,4,3,2,1,2,3,4,5};
auto result = from_array(numbers) >> distinct() >> to_vector();
auto result = empty<int>() >> union_with(range(1,5)) >> to_vector();
int set1[] = {5,4,3,2,1,2,3,4,5};
int set2[] = {4,5,6,7};
auto set3 = from_array(set1) >> union_with(from_array(set2)) >> to_vector(); auto set4 = from_array(set2) >> union_with(from_array(set1)) >> to_vector();
auto result1 = empty<int>() >> intersect_with( range(0, 10) ) >> to_vector(); auto result2 = range(0, 10) >> intersect_with( empty<int>() ) >> to_vector();
int set1[] = {5,4,3,2,1,2,3,4,5};
int set2[] = {4,5,6};
auto set3 = from_array(set1) >> intersect_with(from_array(set2)) >> to_vector(); auto set3 = from_array(set2) >> intersect_with(from_array(set1)) >> to_vector();
auto result1 = empty<int>() >> except( range(0, 10) ) >> to_vector(); auto result2 = range(0, 10) >> except( empty<int>() ) >> to_vector();
int set1[] = {5,4,3,2,1,2,3,4,5};
int set2[] = {4,5,6,7};
auto set3 = from_array(set1) >> except(from_array(set2)) >> to_vector(); auto set4 = from_array(set2) >> except(from_array(set1)) >> to_vector();
You can learn more about these operators (and the others that are implemented) by reading the cpplinq query operators documentation.
CodeProject