Access index in range-for loop

后端 未结 6 455
忘了有多久
忘了有多久 2020-12-24 11:44

I have a vector of objects and am iterating through it using a range-for loop. I am using it to print a function from the object, like this:

vector

        
6条回答
  •  生来不讨喜
    2020-12-24 12:16

    You can use the enumerate view of range-v3:

    std::vector storedValues;
    for (auto const& [idx, value] : storedValues | ranges::view::enumerate) {
      std::cout << idx << ": " << value << '\n';
    }
    

    In C++20 will introduce additional initializations in range-for loops:

    std::vector storedValues;
    for (size_t idx = 0; auto value : storedValues) {
      std::cout << idx << ": " << value << '\n';
      ++idx;
    }
    

提交回复
热议问题