仿函数问题,各位高手请进

mahatma_cn 2005-01-07 05:44:13
我们知道max_element和min_element分别返回一个区间的最大值和最小值。
本来很好用。但是问题来了
我在一个vector中某些地方存放了固定的一个比任何可能出现在vector数组中的值都要大的一个标志位
但是我想在调用以上函数时,这个固定值不作为比较对象,就是说max_element不返回这个固定的标志位。有什么办法?max_element的第三个参数能解决这个问题吗?怎么写这个仿函数呢?
我自己写了一个,但是max_element好像从来不调用!!!



高手请不惜赐教!
...全文
108 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
mahatma_cn 2005-01-07
  • 打赏
  • 举报
回复
明天给分
mahatma_cn 2005-01-07
  • 打赏
  • 举报
回复
谢谢你,搞定。
youngphoneix 2005-01-07
  • 打赏
  • 举报
回复
如果你的那个特殊值每次不同的话可以这样:

struct greater : public binary_function<T, T, bool>
{
greater( const T& x ):value(x) {}

bool operator()( const T& lhs, const T& rhs ) const
{
if( *rhs == value )
return false;
else
return ( lhs > rhs );
}
private:
T value;
};

youngphoneix 2005-01-07
  • 打赏
  • 举报
回复
那就改成
template< typename T >
struct greater : public binary_function<T, T, bool>
{
bool operator()( const T& lhs, const T& rhs ) const
{
if( *rhs == 某个值 )
return false;
else
return ( lhs > rhs );
}
};
mahatma_cn 2005-01-07
  • 打赏
  • 举报
回复
而且不应该纪录个数,因为一个数组中我定义的这个特殊值可能出现在数组任何地方,并且出现次数也是一个未知数!
mahatma_cn 2005-01-07
  • 打赏
  • 举报
回复
你的第二次回答和我写的开始写的一样,可为什么调试的时候max_element不掉用它呢?谢谢你!
mahatma_cn 2005-01-07
  • 打赏
  • 举报
回复
to youngphoneix(雪里红)
我不想重新写一个函数,只想利用标准库的max_element这个函数!就是怎么写第三个参数。
youngphoneix 2005-01-07
  • 打赏
  • 举报
回复

template< typename T >
struct greater : public binary_function<T, T, bool>
{
greater():count(0)

bool operator()( const T& lhs, const T& rhs ) const
{
++count;
if( count != 某个数 )
return ( lhs > rhs );
else
return false;
}

private:
size_t count;
};

youngphoneix 2005-01-07
  • 打赏
  • 举报
回复
template< typename ForwardIterator, typename Compare >
ForwardIterator max_element( ForwardIterator first, ForwardIterator last,
Compare comp )
{
if( first == last )
return first;

ForwardIterator result = first;
for( ; first != last; ++first )
{
if( comp(*result, *first) )
result = first;
}
return result;
}

64,687

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧