C++ 有人能解释一下[](inti){returni%2==0;}是什么意思吗?
在以下STL算法的示例代码C++ 有人能解释一下[](inti){returni%2==0;}是什么意思吗?,c++,algorithm,stl,C++,Algorithm,Stl,在以下STL算法的示例代码std::all_of “[](int i){返回i%2==0;}”是什么意思 int main() { std::vector<int> v{10, 2, 4, 6}; if (std::all_of(v.begin(), v.end(), [](int i){ return i % 2 == 0; })) { std::cout << "All numbers are even\n"; }
std::all_of
“[](int i){返回i%2==0;}”是什么意思
int main() {
std::vector<int> v{10, 2, 4, 6};
if (std::all_of(v.begin(), v.end(), [](int i){ return i % 2 == 0; })) {
std::cout << "All numbers are even\n";
}
else{
std::cout << "All numbers are not even\n";
}
}
int main(){
std::向量v{10,2,4,6};
如果(std::all_of(v.begin(),v.end(),[](int i){return i%2==0;})){
std::cout它是一个检查i
是否为偶数的函数。如果i
为偶数,它将返回true,否则返回false
其逻辑相当于:
#include <algorithm>
#include <iostream>
bool isEven(int i) {
return i % 2 == 0;
}
int main() {
std::vector<int> v{10, 2, 4, 6};
if (std::all_of(v.begin(), v.end(), isEven)) {
std::cout << "All numbers are even\n";
}
else{
std::cout << "All numbers are not even\n";
}
}
#包括
#包括
布尔伊塞文(国际一){
返回i%2==0;
}
int main(){
std::向量v{10,2,4,6};
如果(std::all_of(v.begin(),v.end(),isEven)){
看来我还需要学习这些lambda函数,谢谢you@Lorenzoλ方法可以派上用场,抽象地将其看作一个匿名方法,检查它们并享受乐趣……顺便说一句,欢迎使用堆栈溢出!:)