如何将对象数据成员传递给 C++ 中的 lambda 函数?

How to pass an object data member to a lambda function in C++?

假设我有以下非工作代码(仅用于说明目的):

class fruit
{
    public:

    std::string apple;
    std::string banana;
    std::String orange;
};

class grocery
{
    public:
    
    std::vector<fruit> g_items;
    std::string total_weight;   
};

std::vector<grocery> shopping; 

auto check_item = [&](std::string f_itm) -> void
{
    for (std::size_t i = 0; i < shopping.g_items.size(); ++i)
    {
        std::cout << shopping.g_items.at(i).f_itm << std::endl;
    }
};

check_item(apple);
check_item(banan);
check_item(orange)

如何调用 lambda 函数 check_item,传递 fruit 对象的特定数据成员,因为它们都具有相同的类型 (std:string)?

谢谢。

更改 lambda 以接受指向成员的指针,例如:

class fruit
{
public:
    std::string apple;
    std::string banana;
    std::string orange;
};

class grocery
{
public:
    std::vector<fruit> g_items;
    std::string total_weight;   
};

std::vector<grocery> shopping; 

...

auto check_item = [&](std::string (fruit::*f_itm)) -> void
{
    for (auto &g : shopping)
    {
        for (auto &f : g.g_items) {
            std::cout << f.*f_itm << std::endl;
        }
    }
};

check_item(&fruit::apple);
check_item(&fruit::banana);
check_item(&fruit::orange);

Demo

试试这个:

#include <string>
#include <vector>
#include <iostream>

class fruit
{
public:

    std::string apple;
    std::string banana;
    std::string orange; //std::string, not std::String
};

class grocery
{
public:
    std::vector<fruit> g_items;
    std::string total_weight;
};

std::vector<grocery> shopping;


auto check_item = [&](std::string(fruit::* f_itm)) -> void
{
    for (std::size_t i = 0; i < shopping.size(); ++i) //you have two, vectors, so first iterate through shopping
    {
        for (std::size_t j = 0; j < shopping[i].g_items.size(); ++j) //then, iterate through g_items 
            std::cout << shopping[i].g_items[i].*f_itm << std::endl; //then, print
    }
};

int main() {
    check_item(&fruit::apple); 
    check_item(&fruit::banana); //you put banan, not banana
    check_item(&fruit::orange); //remember the ;
}

您的原始代码有几个错误。然后,在您的 for 循环中,您有两个遍历两个向量,如注释所解释的那样。然后,它应该可以工作。