问题
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.
回答1:
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):
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: http://en.wikibooks.org/wiki/C++_Programming/Operators/Operator_Overloading
回答2:
Some of these already exist and are in the algorithm header:
- set_union
- set_difference
- set_intersection
- set_symmetric_difference
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/
来源:https://stackoverflow.com/questions/6292766/a-generic-set-operations-class-i-e-intersection-union-minus-etc