函数对象 泛型设计 stl c++

来源:百度知道 编辑:UC知道 时间:2024/06/03 21:41:11
#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>
using namespace std;

template< typename Type >
class lessEqualOs:
public binary_function< Type, Type, bool > {
public:
lessEqualOs(
ostream &_os = cout,
const string &_interval = string(),
bool _left = true
): os( _os ), interval( _interval ), left( _left ) {}
bool operator()( const Type &_left, const Type &_right ) const {
bool ret = _left < _right;
if( ret ) {
os <<( left ? _left : _right )<< interval;
}
return ret;
}
private:
ostream &os;
string interval;
bool left;
};//函数对象,比较两个数大小,将较小者或较大者输出

int main() {
vector< int > ivec;
for( int i=0; i<10; ++i ) {
int temp;
cin >> temp;
ivec.push_back( temp );
}
int res = count_if( ivec.beg

可能是因为operator()()被声明为const,而又访问了非const的os和interval成员所至。你把operator()()的const属性去掉试试。
编译错误的大体意思就是:没有为右操作数为const string类型重载"<<"操作符。不知是不是这样呢!

这大概只是个基本的STL问题吧,改成这样不就可以了:
os <<( left ? _left : _right )<< interval.c_str();

缺少头文件
#include <string>

未知的类型导致了编译器找不到<<匹配的模板

g++编译通过,运行正常

能不能把编译错误打出来看看