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++) {
set1.push_back(set2.at(i));
}
return set1;
}
So I want the same thing again but where string
is say my_data_type
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 set_union(...)
function because surely I would need to test for equality on each member of my_data_type
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, ...): http://www.cplusplus.com/reference/algorithm/
Your elements simply need to meet the requirements for STL container elements (see http://msdn.microsoft.com/fr-fr/library/bb385469.aspx):
You can find information about operator overloading (to be implemented in your custom class) on that WikiBook: http://en.wikibooks.org/wiki/C++_Programming/Operators/Operator_Overloading
Some of these already exist and are in the algorithm header:
These all support a comparator function so that you could do it to all your own data types. Or as posted in the other reply make your Containers comply to the STL requirements.
See: http://www.cplusplus.com/reference/algorithm/