【问题标题】:using comparing function使用比较功能
【发布时间】:2013-02-26 20:27:39
【问题描述】:

我有这个功能

std::vector <std::vector <int> > puddles;
std::set <int> is_checked;

size_t M, N;

bool v_compare(int a, int b){
    return puddles[(a-a%M)/M][a%M] < puddles[(b-b%M)/M][b%M];
}

我想找到与puddles 中的最小值相对应的集合元素(我使用i*M+j 作为集合中的键)。所以我试图将我的函数用作min_element的谓词

close(*std::min_element(is_checked.begin(), is_checked.end(), v_compare));

但我收到了这个错误

:113:82: error: no matching function for call to 'min_element(std::set<int>::iterator, std::set<int>::iterator, <unresolved overloaded function type>)'
:113:82: note: candidates are:
/usr/include/c++/4.6/bits/stl_algo.h:6173:5: note: template<class _FIter> _FIter std::min_element(_FIter, _FIter)
/usr/include/c++/4.6/bits/stl_algo.h:6201:5: note: _FIter std::min_element(_FIter, _FIter, _Compare) [with _FIter = std::_Rb_tree_const_iterator<int>, _Compare = bool (TFlood::*)(int, int)]
/usr/include/c++/4.6/bits/stl_algo.h:6201:5: note:   no known conversion for argument 3 from '<unresolved overloaded function type>' to 'bool (TFlood::*)(int, int)'

【问题讨论】:

  • v_compare 是否是某个班级的成员?它在类中的声明是否标记为static?
  • 是的,它是班级成员。我试图将其设为静态,但出现此错误:18:12:错误:在静态成员函数中无效使用成员 'TFlood::M':21:63:错误:来自此位置

标签: c++ stl operator-overloading overloading


【解决方案1】:

指向函数的指针和指向成员函数的指针是有区别的。不是static 的类成员会为您提供指向成员函数的指针。但是std::min_element 只接受指向函数或其他可调用类型的指针,而指向成员函数的指针不符合条件,因为没有指针或对类对象的引用就无法调用它。正如您所发现的,如果您尝试将函数设为static 成员,则它无法访问成员M。 (也许puddles 也是,如果那也是会员的话。)

看起来您使用的是支持 lambda 的 g++ 4.6。所以最简单的解决方案是:

close(*std::min_element(is_checked.begin(), is_checked.end(),
      [this](int a, int b) { return puddles[a/M][a%M] < puddles[b/M][b%M]; }));

(我去掉了减法,因为整数类型的除法总是向零舍入,所以(a-(a%M))/M 总是与a/M 相同的结果。)确保使用-std=c++0x 编译器标志。 lambda 魔术负责“捕获”this 指针,供比较对象以后使用。

【讨论】:

  • 这是标准代码,最新的编译器会以同样的方式处理它。只是它直到 2011 年底才正式标准化,所以一些较旧的编译器不会。如果由于某种原因需要使用旧的编译器,可以标记一个问题 [c+​​+03]。
  • 好的,但仍然存在同样的问题:129:82:警告:lambda 表达式仅适用于 -std=c++0x 或 -std=gnu++0x [默认启用]: 129:83: 错误: 没有匹配函数调用 'min_element(std::set::iterator, std::set::iterator, TFlood::resolve()::)' ./tbricks_3.cpp:129:83: 注意: 候选是: /usr/include/c++/4.6/bits/stl_algo.h:6173:5: 注意: template _FIter std:: min_element(_FIter, _FIter) /usr/include/c++/4.6/bits/stl_algo.h:6201:5: 注意:模板 _FIter std::min_element(_FIter, _FIter, _Compare)
  • 您是否将-std=c++0x 添加到您的编译命令(可能通过Makefile)?
猜你喜欢
  • 1970-01-01
  • 2013-10-03
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
  • 2010-09-20
  • 2020-09-07
相关资源
最近更新 更多