'Passing two parameters at c++ lambda expression
I wanted to get a subset of vector having the same keyword in the vector. The code below works well, if I give the fixed keyword.
auto category_matched = [](Product &p) {
std::string str_return;
p.GetInfo(kINFO_CATEGORY, str_return);
return str_return == "keyword";
};
std::copy_if(list_.begin(), list_.end(),
std::back_inserter(products),
category_matched);
Then I tried replacing "keyword" with string variable, which resulted in error.
auto category_matched = [](Product &p, std::string keyword) {
std::string str_return;
p.GetInfo(kINFO_CATEGORY, str_return);
return str_return == keyword;
};
std::copy_if(list_.begin(), list_.end(),
std::back_inserter(products),
category_matched);
Some of the error messages are like this:
error: no matching function for call to object of type '(lambda at /Users/src/productset.cpp:128:29)'
if (__pred(*__first))
note: candidate function not viable: requires 2 arguments, but 1 was provided
How can I add string variable to the function?
Solution 1:[1]
capture the keyword
std::string keyword = "froodle";
auto category_matched = [&keyword](Product &p) {
std::string str_return;
p.GetInfo(kINFO_CATEGORY, str_return);
return str_return == keyword;
};
Solution 2:[2]
std::copy_if expects a UnaryPredicate. That is to say, it expects a function that takes one argument.
You are supplying a lambda that takes two arguments. That is the source of the error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 康桓瑋 |
| Solution 2 |
