【问题标题】:how to use std::find through ONLY first elements of the vector pair OR a custom vector triplet?如何仅通过向量对的第一个元素或自定义向量三元组使用 std::find?
【发布时间】:2020-05-10 15:22:25
【问题描述】:

我有一个vector<triplet>,其中三元组是自定义数据类型,定义如下:-

struct triplet{
   int in, g, o;  //where in denotes index of a triplet element in the vector<triplet>
}

所以我的vector&lt;triplet&gt; 中有一个元素如下

vector<triplet> v= ({0,4,0},{1,2,0},{2,5,0},{3,4,0});

我有几个关于这个vector&lt;triplet&gt;的查询

  1. 我想使用find_if算法来找出x是否已经存在于v[i].in中的任何一个vector&lt;triplet&gt;中,即我想检查x是否与任何一个匹配in 中的 triplet 出现在 vector&lt;triplet&gt; 中。

我在 Internet 上找不到执行此类查询的示例。如果有替代 find_if 的替代方法,请提及。

【问题讨论】:

    标签: c++ algorithm stl


    【解决方案1】:

    使用 lambda 函数。

    int value_to_find = ...;
    find_if(v.begin(), v.end(), [=](const triplet& t){ return t.in == value_to_find; });
    

    当您出于某种目的需要一次性函数时,lambda 函数是显而易见的选择。

    【讨论】:

    • 这里通过引用捕获三元组(而不是按值)。我们应该使用&amp; 而不是=
    • 三元组未被捕获,作为参数传递给 lambda 函数。捕获的是value_to_find,对于整数,按值捕获即可。
    • 所以我们可以写=value_to_find而不是=吗?对不起..我知道这个问题听起来很傻......但我仍然想确认这个事实。
    • @noobCoder003 非常明智的问题。我自己几乎从不这样做,但我认为按值显式捕获的正确语法只是使用变量名,没有等号[value_to_find](const triplet&amp; t){ return t.in == value_to_find; }
    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多