c++ find_if lambda(时间:2019-05-06 标签:c++find_iflambda)
问题描述
下面的代码有什么问题?如果结构体的第一个成员等于 0,它应该在结构体列表中找到一个元素.编译器抱怨 lambda 参数不是谓词类型.
What is wrong with the code below? It is supposed to find an element in the list of structs if the first of the struct's members equals to 0. The compiler complains about the lambda argument not being of type predicate.
#include <iostream>
#include <stdint.h>
#include <fstream>
#include <list>
#include <algorithm>
struct S
{
int S1;
int S2;
};
using namespace std;
int main()
{
list<S> l;
S s1;
s1.S1 = 0;
s1.S2 = 0;
S s2;
s2.S1 = 1;
s2.S2 = 1;
l.push_back(s2);
l.push_back(s1);
list<S>::iterator it = find_if(l.begin(), l.end(), [] (S s) { return s.S1 == 0; } );
}
推荐答案
代码在 VS2012 上工作正常,只是一个建议,按引用传递对象而不是按值传递:
Code works fine on VS2012, just one recommendation, pass object by reference instead of pass by value:
list<S>::iterator it = find_if(l.begin(), l.end(), [] (const S& s) { return s.S1 == 0; } );
这篇关于时间:2019-05-06 标签:c++find_iflambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:时间:2019-05-06 标签:c++find_iflambda
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
