#include <iostream> #include <string> #include <fstream> #include <cassert> #include <memory> #include <vector> #include <algorithm> #include <iterator> using namespace std; /*函数对象,用来进行小于的比较*/ class lessThan { public: lessThan(){} lessThan(int m):value(m){} int getValue() const { return value; } int setValue(int m) { value = m; } bool operator() (int m) { return m < value; } private: int value; }; int main() { lessThan less(5);//函数对象 int i; vector<int> vec; for (i=0; i<10; i++) { vec.push_back(i); } cout<<"查找小于"<<less.getValue()<<"的元素"<<endl; vector<int>::iterator iter = vec.begin(); while ((iter = find_if(iter, vec.end(), less)) != vec.end()) { cout<<*iter<<" "; iter++; } cout<<endl; } STL中的优先级队列,元素类型为自定义类型时的使用 #include <iostream> #include <string> #include <fstream> #include <cassert> #include <memory> #include <vector> #include <algorithm> #include <iterator> #include <queue> using namespace std; class A { public: A(){} A(int a):m_a(a){} /*必须要重载的<运算符*/ /* bool operator < (A& other) { return m_a < other.m_a; }*/ /*友元函数,感觉必需写成友元的,因为它要重载 bool operator()(const _Ty& _Left, const _Ty& _Right) const { // apply operator< to operands return (_Left < _Right); } */ friend bool operator < (const A& a, const A& b); friend ostream& operator << (ostream& out, const A& other); private: int m_a; }; int main() { priority_queue<A> pd1; priority_queue<A*> pd2; priority_queue<A&> pd3;//不知道为什么A&会出错?想不明白 int i; for(i=0; i<10; i++) { pd1.push(A(i)); pd2.push(new A(i)); } for(i=0; i<10; i++) { cout<<pd1.top()<<" "; pd1.pop(); } cout<<endl; } /*重载输出运算符*/ ostream& operator << (ostream& out, const A& other) { out<<other.m_a; return out; } /*友元函数*/ bool operator < (const A& a, const A& b) { return a.m_a < b.m_a; }