【发布时间】:2014-12-08 11:40:30
【问题描述】:
我遇到了 Equal_range 的这段代码,而且对 C++ 还是很陌生,我不清楚为什么我们需要重载运算符即使我们已经创建了一个新的比较函数。
此外,我们可以使用:
bool compare( const S& s, const S& s2 )
{
return s.number < s2.number;
}
改为。
#include <algorithm>
#include <vector>
#include <iostream>
struct S
{
int number;
char name;
S ( int number, char name )
: number ( number ), name ( name )
{}
// only the number is relevant with this comparison
bool operator< ( const S& s ) const
{
return number < s.number;
}
};
struct Comp
{
bool operator() ( const S& s, int i )
{
return s.number < i;
}
bool operator() ( int i, const S& s )
{
return i < s.number;
}
};
int main()
{
// note: not ordered, only partitioned w.r.t. S defined below
std::vector<S> vec = { {1,'A'}, {2,'B'}, {2,'C'}, {2,'D'}, {4,'G'}, {3,'F'} };
auto p = std::equal_range(vec.begin(),vec.end(),2,Comp());
for ( auto i = p.first; i != p.second; ++i )
std::cout << i->name << ' ';
}
编辑:代码的链接是http://en.cppreference.com/w/cpp/algorithm/equal_range
【问题讨论】:
标签: c++ stl operator-overloading