lundi 22 juillet 2019

C++ lambda function - how to return closest vector element compared to target

I have a already-sorted vector called vec, and a target variable. The goal is to return the closest-to-target vector element.

I tried to use C++11 lambda function with [=] to capture outside variable

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec{1,2,3,4,5};
    double target = 3.14159;

    int res = min(vec.begin(), vec.end(), [=](int v1, int v2) -> bool {
            return abs(v1-target) < abs(v2-target);
        });

    cout << res << endl;

    return 0;
}

I expect to get res=3, but it returns an error:

error: cannot convert 'const __gnu_cxx::__normal_iterator<int*, std::vector<int> >' to 'int' in initialization

Aucun commentaire:

Enregistrer un commentaire