如何在包含类的向量中使用 std::less,所有谷歌结果都带有纯 int 示例。
谈到课程,例如:
class A{
public:
A( int value = 0 ):m_value(value){};
int m_value;
};
如何执行以下操作:
std::count_if( m_cells.begin(), m_cells.end(), std::less< int >() );
Less 将收到 A,而不是 int。std::less< A >
似乎 less 需要一个仿函数operator()()
,如何避免这种情况?我需要实现 operator<( int a ) 吗?做个绑定?还有什么?
代码:
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
这导致:
/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]