排序自定义类指针的向量

时间:2015-06-22 23:29:35

标签: c++ sorting c++11 vector

我有vector<FPGA*> current_generation_,我希望FPGA成员fitness_使用sort_members功能对其进行排序。适用的代码如下:

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 ++并不是非常熟悉,这种规模和复杂性的编译器错误让我感到困惑。

如果需要,我可以提供更多上下文。谢谢!

编辑:破折号。

编辑编辑:我搞砸了,并试图对错误的成员进行排序。万岁。

1 个答案:

答案 0 :(得分:3)

我看到的唯一错误是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实例,因为你向对象本身添加了一些语义,这可能是有用的。

相关问题