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

前端 未结 10 577
[愿得一人]
[愿得一人] 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:40

    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; 
    });
    
    0 讨论(0)
  • 2020-12-28 14:43

    Alternatively, you can use &value - &data[0], although it might be a bit more expensive.

    std::for_each(data.begin(), data.end(), [&data](float const& value) {
        int idx = &value - &data[0];
    });
    
    0 讨论(0)
  • 2020-12-28 14:44

    You could also pass a struct as third argument to std::for_each and count the index in it like so:

    struct myStruct {
       myStruct(void) : index(0) {};
       void operator() (float i) { cout << index << ": " << i << endl; index++; }
       int index;
    };
    
    int main()
    {
    
       std::vector data;
       data.push_back(1.0f);
       data.push_back(4.0f);
       data.push_back(8.0f);
    
       // lambda expression
       std::for_each(data.begin(), data.end(), myStruct());
    
       return 0;
    }
    0 讨论(0)
  • 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<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
    });
    
    0 讨论(0)
提交回复
热议问题