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

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

提交回复
热议问题