Johnyb
Johnyb

Reputation: 1316

Using lambda on lower_bound

I am trying to use lambda on lower_bound in c++. I have defined a struct

struct Mop{
    Mop( string n, int a){
        name = n;
        age  = a;
    }
    string name;
    int     age;
    bool operator < ( const Mop&a) const {
        return age < a.age;
    }
};

and add function

void AddVector(vector<Mop> &a, string n , int aa){
    Mop mop(n,aa);
    auto it = lower_bound(a.begin(), a.end(), aa , [](const Mop &ar, const Mop &br){ return ar < br;});
    a.insert(mop,it);
}
int main()
{
    vector<Mop> a;
    AddVector(a,"John",15);
    AddVector(a,"Swan",10);
    return 0;
}

But it keep throwing error regarding lambda :

error: no matching function for call to 'lower_bound(std::vector<Mop>::iterator, std::vector<Mop>::iterator, int&, AddVector(std::vector<Mop>&, std::string, int)::__lambda0)'

I have been searching and the lambda syntax should be corect , why does it keep throwing the error? I tried adding

ar.age and br.age

to lambda didn't work either.

Whats wrong this lambda?

Upvotes: 2

Views: 3129

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726659

You created mop object to use as a comparison key, but you are passing aa instead, which represents the "raw" age:

auto it = lower_bound(a.begin(), a.end(), aa , [](const Mop &ar, const Mop &br){ return ar < br;});
//                                        ^^
a.insert(mop,it);
//       ^^^ ^^
// Arguments are swapped

should be

auto it = lower_bound(a.begin(), a.end(), mop, [](const Mop &ar, const Mop &br){ return ar < br;});
//                                        ^^^
a.insert(it, mop);
//       ^^  ^^^

Demo.

Upvotes: 4

songyuanyao
songyuanyao

Reputation: 172934

The lambda syntax is correct, the problem is the 3rd argument passed to std::lower_bound, it should be value to compare the element of the vector<Mop>, i.e. a Mop, not an int.

BTW: a.insert(mop,it); should be a.insert(it, mop);.

Upvotes: 1

Related Questions