Search code examples
c++higher-order-functionsstl-algorithm

Cannot compile comparison function for vector of pointers


I have the following setup:

std::vector<Data2DController*> controllers2d; // this is defined in the header 

        bool comp(const Data2DController* c1, const Data2DController* c2) {
        return true;
    };

    inline std::vector<Visualizer*> MainController::gatherVisualizers() const {
        std::vector<Visualizer*> visualizers;

        // selected only the biggest cooridante system
        Data2DController* biggestRadiusController = *std::max(controllers2d.begin(), controllers2d.end(), comp);

        visualizers.push_back(biggestRadiusController->getCoordinatesVisualizer());

        return visualizers;
    }

Currently my functions really look like this, everything else is commented out for the sake of simplicity.

Unfortunately, I am getting the following error (there are 4 identical ones for the two input arguments):

Error   5   error C2664: 'bool (Controllers::Data2DController *,Controllers::Data2DController *)' : cannot convert argument 1 from 'const std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<Controllers::Data2DController *>>>' to 'Controllers::Data2DController *'  C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xutility 521 1   

I have no idea why it doesn't compile, all examples I could find with comparison function passed on the algorithm applied on a vector of pointer looked pretty much the same.


Solution

  • std::max(controllers2d.begin(), controllers2d.end(), comp); would compare the iterator (and comp would compare the element (the pointer in your case) so the compile error).

    std::max_element(controllers2d.begin(), controllers2d.end(), comp); would compare the pointer (as comp).