我不知道为什么这两条线有效

int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
    int idx = ruleKey == "type" ? 0 : ruleKey == "color" ? 1 : 2, res = 0;
    return count_if(begin(items), end(items), [&](const auto &i) { return i[idx] == ruleValue; });
}

这是 leetcode 的一个问题。我附上了下面的链接。

我会试着说出我的想法,如果有什么不对的 - 请纠正我。

首先,我们正在创建一个int名为的变量idx。我们为其分配当前值ruleKey(当前是一个字符串)。如果字符串是"type",我们分配idx的值0。如果字符串是"color",我们分配idx的值1。如果这两个条件都不通过,我们分配idx的值2

我不知道为什么res = 0甚至在代码中,我也不知道下面的代码行发生了什么。尤其是[&](const auto &i)代码部分。

回答

我会试着说出我的想法,如果有什么不对的 - 请纠正我。

你对idx变量的理解是正确的。

我不知道为什么res = 0甚至在代码中

它只是声明了一个res初始化为 0的未使用变量。可以在同一个表达式中声明多个相同类型的变量,例如:

int a = 0, b = 1;

在这种情况下, yesres并不真正属于并且可以安全地删除。

我不知道下面的代码行发生了什么。尤其是[&](const auto &i)代码部分。

请参阅std::count_if()算法和Lambda 表达式的文档。

简而言之,std::count_if()循环遍历一个范围,为每个元素调用一个谓词,并在每次谓词返回时递增结果true。代码为该谓词使用了 lambda,即匿名函数类型。

因此,代码正在迭代items向量,计算其内部向量元素中有多少具有与ruleValue指定的索引匹配的值idx。代码基本上等价于:

int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
    int idx;
    if (ruleKey == "type") idx = 0;
    else if (ruleKey == "color") idx = 1;
    else idx = 2;

    int count = 0;
    for(auto iter = items.begin(), end = items.end(); iter != end; ++iter) {
        const auto &i = *iter;
        if (i[idx] == ruleValue) ++count;
    }
    return count;
}


以上是我不知道为什么这两条线有效的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>