ale ale - 7 months ago 50
C Question

A generic set operations class i.e. intersection, union, minus etc

I want to write a C++ class that offers set operations that work on vectors of strings and vectors of my own data type. Are there any easy ways of doing this rather than writing a different function for each data type? So far I have written operations for string vectors. Below shows an example of my set union:

vector<string> SetOperations::set_union(vector<string> set1,
vector<string> set2) {
for(std::vector<int>::size_type i = 0; i < set1.size(); i++) {
return set1;

So I want the same thing again but where
is say
which is a struct of various members. Let's say it looks like this:

struct my_data_type {
int label;
vector<string> x;
vector<string> y;
string str;

A function for each data type would also not be as simple as my
function because surely I would need to test for equality on each member of
in the case of set intersection?

Also, I'm quite new to C++ so any comments on my existing function would be appreciated too.

Many thanks.


There are already such algorithms (union, intersection, sorting, ...):

Your elements simply need to meet the requirements for STL container elements (see

All reference types that are inserted into STL/CLR containers must have, at a minimum, the following elements:

A public copy constructor.

A public assignment operator.

A public destructor.

Furthermore, associative containers such as set and map must have a public comparison operator defined, which is operator< by default. Some operations on containers might also require a public default constructor and a public equivalence operator to be defined.

Like reference types, value types and handles to reference types that are to be inserted into an associative container must have a comparison operator such as operator< defined. The requirements for a public copy constructor, public assignment operator, and a public destructor do not exist for value types or handles to reference types.

You can find information about operator overloading (to be implemented in your custom class) on that WikiBook: