我有vector<FPGA*> current_generation_,我想使用sort_members函数按FPGA成员fitness_进行排序。适用的守则如下:
bool sort_members (FPGA* fpga_first, FPGA* fpga_second) {
return (fpga_first->fitness() < fpga_second->fitness());
};fpga.hpp
#include <vector>
class FPGA {
public:
explicit FPGA(int input_gates, int output_gates, int normal_gates);
const int fitness();
protected:
int fitness_;
};fpga.cpp
FPGA::FPGA() {
this->fitness_ = 0;
}
const int FPGA::fitness() {
return this->fitness_;
}执行情况:
std::sort(this->current_generation_.begin(), this->current_generation_.end(), sort_members);错误:
/usr/include/c++/4.9/bits/stl_algo.h: In instantiation of ‘void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::__detail::_Node_iterator<std::pair<const int, FPGA*>, false, false>; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<bool (*)(FPGA*, FPGA*)>]’:
/usr/include/c++/4.9/bits/stl_algo.h:4717:78: required from ‘void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = std::__detail::_Node_iterator<std::pair<const int, FPGA*>, false, false>; _Compare = bool (*)(FPGA*, FPGA*)]’
/usr/include/c++/4.9/bits/stl_algo.h:1968:22: error: no match for ‘operator-’ (operand types are ‘std::__detail::_Node_iterator<std::pair<const int, FPGA*>, false, false>’ and ‘std::__detail::_Node_iterator<std::pair<const int, FPGA*>, false, false>’)
std::__lg(__last - __first) * 2,总错误字符串的其余部分是巨大的,但我相信大部分是编译器认为(错误的)是候选的。我对c++并不十分熟悉,一个如此庞大和复杂的编译器错误让我感到困惑。
如果需要,我可以提供更多的上下文。谢谢!
编辑:破折号。
编辑:我搞砸了,并试图对错误的成员排序。万岁。
发布于 2015-06-22 23:35:54
我看到的唯一错误是this>current_generation_.end(),而不是->。
此外,您应该考虑将您的比较函数声明为接受两个const FPGA*而不是FPGA*。这将迫使您将fitness()声明为const int fitness() const,但拥有const是有意义的。
请注意,由于您使用的是C++11,所以可以直接使用lambda:
std::sort(data.begin(), data.end(), [](const FPGA* f1, const FPGA* f2) { ... });您还可以选择直接重载operator<:
class FPGA {
...
bool operator<(const FPGA* other) const { return fitness_ < other->fitness_; }
}
std::sort(data.begin(), data.end());如果没有其他条件来比较两个FPGA实例,这可能很有用,因为您向对象本身添加了一些语义。
https://stackoverflow.com/questions/30991553
复制相似问题