如何使用for_each获取向量中的值的索引? [英] How to get the index of a value in a vector using for_each?

查看:143
本文介绍了如何使用for_each获取向量中的值的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码(编译器:MSVC ++ 10):

I have the following code (compiler: MSVC++ 10):

std::vector<float> data;
data.push_back(1.0f);
data.push_back(1.0f);
data.push_back(2.0f);

// lambda expression
std::for_each(data.begin(), data.end(), [](int value) {
     // Can I get here index of the value too?
});

我想在上面的代码片段中获取数据向量中的值的索引lambda表达式。似乎for_each只接受一个参数函数。使用for_each和lambda有什么替代方法吗?

What I want in the above code snippet is to get the index of the value in the data vector inside the lambda expression. It seems for_each only accepts a single parameter function. Is there any alternative to this using for_each and lambda?

推荐答案

我不认为你可以捕获索引,使用外部变量进行索引,将其捕获到lambda中:

I don't think you can capture the index, but you can use an outer variable to do the indexing, capturing it into the lambda:

int j = 0;
std::for_each(data.begin(), data.end(), [&j](float const& value) {
            j++;
});
std::cout << j << std::endl;

这样打印3个符合预期, j 保存索引的值

This prints 3, as expected, and j holds the value of the index.

如果你想要实际的迭代器,你也可以这样做:

If you want the actual iterator, you maybe can do it similarly:

std::vector<float>::const_iterator it = data.begin();
std::for_each(data.begin(), data.end(), [&it](float const& value) {
            // here "it" has the iterator
            ++it; 
});

这篇关于如何使用for_each获取向量中的值的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆