How to use std::less in a vector that contains classes, all google results are with plain int examples.
When it comes to classes, for example:
class A{
public:
A( int value = 0 ):m_value(value){};
int m_value;
};
How to do something like:
std::count_if( m_cells.begin(), m_cells.end(), std::less< int >() );
Less will receive an A, not an int. std::less< A >
Seems like less needs a functor operator()(), how to avoid this? I need to implement operator<( int a ) ? Make a bind? What else?
Code:
1 #include <iostream>
2 #include <vector>
3 #include <algorithm>
4
5 using namespace std;
6
7 class A
8 {
9 public:
10 A(int a = 0 ):m_value(a) {}
11 bool operator!=( int a )
12 {
13 return m_value != a;
14 }
15
16 bool operator<( A &a )
17 {
18 return m_value < a.m_value;
19 }
20
21 int m_value;
22 };
23
24
25 int main(){
26 std::vector< A > m_cells( 5 );
27
28 m_cells[2].m_value = 3;
29 m_cells[3].m_value = 4;
30 m_cells[4].m_value = 4;
31 std::count_if( m_cells.begin(), m_cells.end(), std::less< A >() );
32 return 0;
33 }
34
This results in:
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_algo.h:4437: error: no match for call to ‘(std::less<A>) (A&)’
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_function.h:229: note: candidates are: bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = A]
Implement an
operator<forA, and then pass instd::less<A>, other options (for example you could implement a conversion operator toint– YUCKYUCKYUCKYUCK)EDIT: To continue…
Like James says,
std::less<>requires two arguments, if you are stuck on c++03 (and don’t have boost), you can do something like the following:Basically one of the arguments is bound to
3– this the first argument (consider the left hand side), you can also bind to the second argument (right hand side – usingstd::bind2nd), depending on how you want the predicate to work.This approach requires that you properly implement
operator<, i.e.EDIT2: for c++11, you can try any of the following: