How to get the index of a value in a vector using

2019-02-02 22:15发布

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?
});

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?

标签: c++ c++11 lambda
10条回答
姐就是有狂的资本
2楼-- · 2019-02-02 22:44

maybe in the lambda function, pass it a int& instead of value int, so you'd have the address. & then you could use that to deduce your position from the first item

would that work? i don't know if for_each supports references

查看更多
【Aperson】
3楼-- · 2019-02-02 22:46

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;

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; 
});
查看更多
该账号已被封号
4楼-- · 2019-02-02 22:50

I think that the simplest way is to use std::accumulate:

std::accumulate(data.begin(), data.end(), 0, [](int index, float const& value)->int{
    ...
    return index + 1;
});

This solution works with any container and it don't require a variable or custom classes.

查看更多
一纸荒年 Trace。
5楼-- · 2019-02-02 22:50

Following the standard convention for C and C++, the first element has index 0, and the last element has index size() - 1.

So you have to do the following;-

std::vector<float> data;
int index = 0;

data.push_back(1.0f);
data.push_back(1.0f);
data.push_back(2.0f);

// lambda expression
std::for_each(data.begin(), data.end(), [&index](float value) {
// Can I get here index of the value too?
   cout<<"Current Index :"<<index++; // gets the current index before increment
});
查看更多
登录 后发表回答