Using the <algorithm> library for arbitrary data types

I used to ask this question , which concerned how to make my own class of given operations, for example. intersection, union, etc.

The answer that I chose as my solution recommended a library of algorithms that are already implemented. I want these operations to work on my data types as follows:

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

therefore, it was suggested that these things be included in my structure (or class):

  • Public Copy Designer.
  • Public assignment operator.
  • Public destructor.

I'm relatively new to C / C ++, so please can anyone provide me with these three things for the struct example that I defined here? Then also how to use one of the operations on my class (say set_intersection(...)?

Thank.

+3
source share
1 answer

In this case, the compiler provides a suitable implementation of all three - there is no need to write anything superfluous, and it will be a bad style, IMHO. However, you probably need a constructor that takes parameters, builds a properly initialized object, and an implementation of the <() operator so that your structures can be compared.

Not knowing what your structure does, it's hard to provide them, but if your members will have unique labels, then here 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;
    }
};
+2
source

All Articles