c++ std::find custom comparator doesn't work

1.7k Views Asked by At

I am learning how to use std::find with custom comparator now.

However, by following the guidance on-line, I am facing a compiler error.

Link to my code.

Below is my code:

    #include <iostream>
    #include <algorithm>
    #include <pair.h>
    #include <vector>

    using namespace std;

    int main()
    {
        struct comp
        {
            comp(const int& input) : _input(input) {}
            bool operator()(const pair<int, int>& iPair)
            {
                return (iPair.first == _input);
            }
            int _input;
        };

        pair<int, int> pair1(1,3);
        pair<int, int> pair2(2,4);

        vector<pair<int, int> > vec;
        vec.push_back(pair1);
        vec.push_back(pair2);

        vector<pair<int,int> >::iterator it = find(vec.begin(), vec.end(), comp(1));
        if(it != vec.end())
        {
            cout << it->second << endl;
        }

        return 0;
    }

Error is listed below:

In function 'int main()':
Line 27: error: no matching function for call to 'find(__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<std::pair<int, int>*, __gnu_norm::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >, __gnu_debug_def::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >, __gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<std::pair<int, int>*, __gnu_norm::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >, __gnu_debug_def::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >, main()::comp)'
compilation terminated due to -Wfatal-errors.

Many thanks in advance.

1

There are 1 best solutions below

4
On BEST ANSWER

std::find doesn't take a custom comparator. You need to use std::find_if:

auto it = find_if(vec.begin(), vec.end(), comp(1));