gpt4 book ai didi

c++ - 如何使用 operator[] 访问结构的指定字段值

转载 作者:行者123 更新时间:2023-11-27 23:47:35 25 4
gpt4 key购买 nike

假设我有一个带有 bool 字段的结构

struct pBanana {        
bool free;
};

现在我有另一个包含 pBanana 结构 vector 的结构

struct handler_toto {

std::vector<pBanana > listBananas;

};

现在我很想返回 listBananas 中 boolean free 为 false 的次数

int someFunction (mainHandler& gestionnaire)
{
return std::count(gestionnaire.listBananas.begin(), gestionnaire.listBananas.end(), gestionnaire.listBananas.operator[/*How to do it here */]);
}

经过咨询documentation我很难理解如何在我的案例中正确使用 operator[]

最佳答案

那是因为您不能使用 operator[] 来执行此操作。

您可以使用 std::count_if(不是 count)和 lambda 函数 a.k.a.匿名函数:

return std::count_if(
gestionnaire.listBananas.begin(),
gestionnaire.listBananas.end(),
[](const pBanana &b) {return b.free;});

std::count_if 将为列表中的每个项目调用您的函数,并计算它返回 true 的次数。

关于c++ - 如何使用 operator[] 访问结构的指定字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com