I am having some trouble with the sort function… here is my code:
class Parola {
public:
string s;
int repetition;
bool operator()(const Parola *x, const Parola *y) {
return x->repetition > y->repetition;
}
};
int main(int argc, char** argv) {
...
vector<Parola> p;
...
some insertions here
...
sort(p.begin(), p.end(), Parola());
...
return 0;
}
Why I can’t compile this without errors?
Thanks a lot!
PS: I will show you only the first three lines of over fifty of errors:
/usr/include/c++/4.2.1/bits/stl_algo.h: In function 'const _Tp& std::__median(const _Tp&, const _Tp&, const _Tp&, _Compare) [with _Tp = Parola, _Compare = Parola]':
/usr/include/c++/4.2.1/bits/stl_algo.h:2795: instantiated from 'void std::__introsort_loop(_RandomAccessIterator, _RandomAccessIterator, _Size, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Parola*, std::vector<Parola, std::allocator<Parola> > >, _Size = long int, _Compare = Parola]'
/usr/include/c++/4.2.1/bits/stl_algo.h:2866: instantiated from 'void std::sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Parola*, std::vector<Parola, std::allocator<Parola> > >, _Compare = Parola]'
Giving the OP some options to choose from: (note: not exhaustive)
Option 1: Internal operator <()
called using the default std::less<> template.
Option 2: Internal Functional operator()():
called with optional comparison object, as dasblinken pointed out, odd, but works:
Option 3: External operator <()
This, like (1), uses the default std::less<> comparator, but requires that the external operator also be a friend of class Parola to have access to the private data members if declared as such. Its use is the same as (1).
Option 4: External Functor
And used by:
Like (3), the CompareParola class must be friended to Parola if the members being accessed are private:
Option 5: External Function
Similar to an external operator or external functional class, this also requires being friended to the object class to gain access to the private members. Invoked like such:
Option 6: Static Class Function
This is often under-utilized, and has the very nice attribute of having access to all the object member variables, including private ones (obviously, its defined with the class). You can use this by doing:
Note that this, like (1) and (2), keeps everything in the class.
Of all of these I prefer (1) for its simplicity, and (4) for its independence, but everyone has their tastes. There are times that (5) or (6) really comes in handy (and I’m a personal fan of (6)).
If you can think of any more and have the rep to edit it, kindly update this as needed. Please do try to make them at least somewhat useful =P