You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将迭代器传入Lambda函数以处理目标元素?

在Lambda中获取vector匹配元素的迭代器索引

针对你的需求,这里提供几种实用的实现方式:

方式一:用std::for_each遍历处理

直接遍历整个vector,在Lambda里利用vector内存连续的特性,通过元素地址计算当前迭代器的位置,遇到目标元素时输出索引:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main() {
    std::vector<int> input = {11, 12, 15, 11, 13};
    int target = 11;

    std::for_each(input.begin(), input.end(), [&input, target](const int& val) {
        if (val == target) {
            auto current_it = input.begin() + (&val - &input[0]);
            int index = std::distance(input.begin(), current_it);
            std::cout << "目标元素索引:" << index << std::endl;
        }
    });

    return 0;
}

方式二:循环调用std::find_if找所有匹配项

这种方式适合逐个查找所有目标元素,Lambda负责判断匹配条件,外部循环中直接计算迭代器对应的索引:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main() {
    std::vector<int> input = {11, 12, 15, 11, 13};
    int target = 11;

    auto it = input.begin();
    while ((it = std::find_if(it, input.end(), [target](int val) {
        return val == target;
    })) != input.end()) {
        int index = std::distance(input.begin(), it);
        std::cout << "目标元素索引:" << index << std::endl;
        ++it; // 移动迭代器,继续查找下一个匹配元素
    }

    return 0;
}

方式三:结合索引遍历+Lambda

如果不需要依赖迭代器,直接通过索引遍历vector,在Lambda中直接使用索引值:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> input = {11, 12, 15, 11, 13};
    int target = 11;

    for (size_t i = 0; i < input.size(); ++i) {
        [&input, target, i]() {
            if (input[i] == target) {
                std::cout << "目标元素索引:" << i << std::endl;
            }
        }();
    }

    return 0;
}

关键说明

Lambda默认只接收元素值,没法直接拿到迭代器,所以要么通过元素地址转换(vector内存连续,该方法可靠),要么在外部循环中结合迭代器处理。如果要查找所有匹配元素,方式二是最实用的选择。

内容的提问来源于stack exchange,提问作者PIYUSH TAILOR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 13:45:06