C++ C++;lambda语法

C++ C++;lambda语法,c++,lambda,C++,Lambda,我有一个函数,它搜索迭代器向量,如果迭代器的名称与作为参数传递的字符串匹配,则返回迭代器 koalaGraph::PVertex lookUpByName(std::string Name, std::vector<koalaGraph::PVertex>& Vertices) { for (size_t i = 0; i < Vertices.size(); i++) { if(Vertices[i]->info.name == Na

我有一个函数,它搜索迭代器向量,如果迭代器的名称与作为参数传递的字符串匹配,则返回迭代器

koalaGraph::PVertex lookUpByName(std::string Name, std::vector<koalaGraph::PVertex>& Vertices) {

    for (size_t i = 0; i < Vertices.size(); i++) {

        if(Vertices[i]->info.name == Name) 
            return Vertices[i];
    }
}
但是上面说的是
V

封闭函数局部变量不能在lambda主体中引用,除非它位于捕获列表中


std::find_if
的谓词将依次接收对范围中每个元素的引用。你需要:

std::find_if(
    V.begin(), V.end(),
    [&Name](koalaGraph::PVertex const &v) { return Name == v->info.name; }
);

如果要将向量的元素传递到lambda中,则查找。这意味着你需要

std::find_if(V.begin(), V.end(), [&Name](auto const& V) {return Name == V->info.name;})
因此lambda体中的
V
是向量的元素,而不是向量本身


理想情况下,您应该给它一个不同于
V
的名称,以便将向量和局部变量分开

std::find_if(V.begin(), V.end(), [&Name](auto const& element) {return Name == elememt->info.name;})

现在很明显,您正在处理向量的一个元素,而不是向量本身。

Get
V
作为lambda的参数


std::find_如果(V.begin()、V.end()、[&Name](type&V){return Name==V->info.Name;)
首先,
V->info.Name
在lambda内部或外部格式不正确

发送到algoritm
std::find_if
的函数对象必须是一元函数。它必须将要检查的当前元素作为参数

auto found = std::find_if(
    V.begin(), V.end(), 
    [&Name](koalaGraph::PVertex const& item_to_check) {
        return Name == item_to_check->info.name;
    }
);
found
的类型是已找到元素的迭代器。如果未找到,则返回
V.end()

如果使用C++14或更高版本,甚至可以使用通用lambda:

auto found = std::find_if(
    V.begin(), V.end(), 
    [&Name](auto const& item_to_check) {
        return Name == item_to_check->info.name;
    }
);

使用
const auto&
访问lambda表达式中向量中的各个元素。由于向量是左值,auto将被推导为
const vector&
。然后,您可以使用
std::distance
查找向量中对象的元素位置

struct PVertex
{
    std::string name;
};

int main()
{
    std::vector<PVertex> V = {{"foo"},{"bar"},{"cat"},{"dog"}};

    std::string Name = "cat";

    auto found = std::find_if(std::begin(V), std::end(V), [&Name](const auto &v){return (Name == v.name);});

    std::cout<< "found at: V["<<std::distance(std::begin(V),found)<<"]" <<std::endl;
}

示例:

V->info.name
是有效语法。它只是不会进行类型检查,因为向量不会重载
->
它只是不会进行类型检查,因为向量不会重载->
所以…它不会编译?在类型的对象上使用
->
是无效语法,而类型的对象不会重载
运算符->
并非所有编译错误rs是语法错误。请参阅。@SilvioMayolo您链接我的答案说,语义是程序的含义,通常在程序的运行时行为中。我引用的代码只是格式不正确,还没有语义。或者可能我不理解这个概念。如果找不到任何内容,请更正Lyno
return
struct PVertex
{
    std::string name;
};

int main()
{
    std::vector<PVertex> V = {{"foo"},{"bar"},{"cat"},{"dog"}};

    std::string Name = "cat";

    auto found = std::find_if(std::begin(V), std::end(V), [&Name](const auto &v){return (Name == v.name);});

    std::cout<< "found at: V["<<std::distance(std::begin(V),found)<<"]" <<std::endl;
}
found at: V[2]