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

前端 未结 10 725
[愿得一人]
[愿得一人] 2020-12-28 14:02

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

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

// lambda          


        
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 14:46

    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 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 :"<

提交回复
热议问题