How lambda function in set algorithms in C++ really works?

78 Views Asked by At

I am curious about how std algorithms interpret lambda expressions. In below example I am using std::set_difference algorithm for two maps. But the question is common for all algorithms vs comparison function.

    std::map<std::string, int> map1{ {"test1",1}, {"test2",2}, {"test3",3}, {"test4",4},{"wxyz5",10}};
    std::map<std::string, int> map2{ {"test1",2}, {"test2",3} };

    std::map<std::string, int> difference;

    std::set_difference(map1.begin(), map1.end(), map2.begin(), map2.end(), std::inserter(difference, difference.begin()), [](const auto& one, const auto& two) { return one.first < two.first; }); 

I am getting correct output , {"test3",3}, {"test4",4},{"wxyz5",10}.

question is, if the comparison function returns true will the first element be added to output ?

If that is the case , I tried this in lambda return return one.first != two.first it breaks with assertion sequence not ordered. Here I am expecting that if keys are not same in both the maps then , return true , and the first element should be added to output. but it is not working .

Probably my way of understanding how each algorithm interprets lambda expression is wrong. Can anyone please explain .

thanks.

0

There are 0 best solutions below