Using the <algorithm> library on arbitrary data types
Earlier I asked this question which was on how to make my own set operations class e.g. intersection, union etc.
The answer I chose as my solution recommended the algorithm library which have these operations already implemented. I want to get these operations working on my data types like this:
struct my_data_type {
int label;
vector<string> 开发者_StackOverflow社区x;
vector<string> y;
string str;
};
so it was suggested that I include these things in my struct (or class):
- A public copy constructor.
- A public assignment operator.
- A public destructor.
I'm relatively new to C/C++ so please could someone provide me with these three things for the example struct that I defined here? Then also how to use one of the operations on my class (let's say set_intersection(...)
?
Thank you.
The compiler provides a suitable implementation of all three in this case - there is no need to write anything extra, and doing so would be bad style, IMHO. However, what you probably do need is a constructor that takes parameters, to construct a properly initialised object, and an implementation of operator<() so that your structs can be compared.
Without knowing what your struct does, it's hard to provide these, but assuming your set members will have unique labels, something like this is what you need:
struct my_data_type {
int label;
vector<string> x;
vector<string> y;
string str;
my_data_type( int l, const string & s ) : label( l ), str( s ) {}
bool operator<( const my_data_type & t ) const {
return label < t.label;
}
};
精彩评论