我有一段代码,仅当人口大于500万时才返回城市名称和人口。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
template <typename C>
static auto opt_print(const C& container) {
return [end_it (end(container))] (const auto& item) {
if (item != end_it) {
cout << *item << endl;
}
else {
cout << "<end>" << endl;
}
};
}
struct city {
string name;
unsigned population;
};
bool operator==(const city& a, const city& b) {
return (a.name == b.name && a.population == b.population);
}
ostream& operator<<(ostream& os, const city& c) {
return os << "{" << c.name << ", " << c.population << "}";
}
int main() {
const vector<city> c {
{"NYC", 8398748},
{"LA", 3990456},
{"Chicago", 2705994},
{"Houston", 2325502}
};
auto print_city (
opt_print(c)
);
auto population_more_than (
[] (unsigned i) {
return [=] (const city& item) {
return (item.population > i);
};
}
);
auto found_large(
find_if(
begin(c),
end(c),
population_more_than(5000000)
)
);
print_city(found_large);
return 0;
}
我有以下问题:
population_more_than
:为什么我需要2层lambda函数?有没有一种简化代码的方法? [=]
在这里做什么?通过lambda函数定义,[=]
表示按值接受所有外部变量,此[=]
接受什么?它仅从外层获取unsigned i
部分吗? population_more_than
lambda函数更改为以下内容:
auto population_more_than (
[&each_city] (unsigned i) {
return (each_city.population > i);
}
);
我应该如何相应地更改auto found_large
lambda函数部分?它已经基于迭代器,但是我无法运行代码。最佳答案
What I don't understand is the lambda function population_more_than: why do I need 2 layers of lambda functions? Is there a way of simplifying code?
它将传递
int
与传递city
分开。请注意,稍后会将多个城市与相同的int
进行比较。 std::find_if
需要像bool(city)
这样的可调用对象,而不是bool(city, int)
What does [=] do here? By lambda function definition, [=] means the accept all external variables by value, what does this [=] accept? Does it only take the unsigned i part from the outer layer?
是。
If I want to change the population_more_than lambda function to below:
auto population_more_than ( [&each_city] (unsigned i) { return (each_city.population > i); } );
How should I change theauto found_large
lambda function part accordingly?
found_large
不是lambda。它是std::vector<city>::const_iterator
。要使用population_more_than
,您需要一些int
进行调用,并且在city each_city;
之前定义了population_more_than
关于c++ - Lambda函数中的C++ 2层返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61512811/