0

Since C++11 there is a cool way to iterate through the containers using for range loop. This version is recommended by lots of C++ gurus such as Herb Sutter, Scott Meyers, Jason Turner, etc. But suppose we need to extract the indices of the certain value of std::vector, so in that case what code snippet is preferable overall, taking into account all main criteria of C++ good coding(readability, efficiency, memory, etc.)?

Version 1:

    for(size_t id = 0; id < myVec.size(); ++id) {
      //extracting indices with a certain value
    }

or

Version 2:

{
  size_t id = 0;
  for(auto& elem : myVec) {
    //extracting indices with a certain value
    ++id;
  }   
}
Hayk
  • 27
  • 3
  • 3
    If you actually need the indices, don't use the range-based for. Pointless to reinvent the original style of the loop when it still works and is applicable to the code you want to write. – Nathan Pierson Feb 22 '22 at 20:55
  • Probably opinion-based. But, if you have C++20 or later, you can use a "hybrid" form: `for (size_t id = 0; auto& elem : myVec) {` – Adrian Mole Feb 22 '22 at 20:55
  • [This question](https://stackoverflow.com/questions/10962290/how-to-find-the-index-of-current-object-in-range-based-for-loop) has some more suggestions how to do this, also in newer versions of C++. – user17732522 Feb 22 '22 at 21:00

0 Answers0