Home > Mobile >  Get iterator to beginning of function-generated range within for loop
Get iterator to beginning of function-generated range within for loop

Time:08-04

I am trying to get an iterator to the beginning of a for loop, in which the range is generated by a function:

std::vector<int> buildList() {...}

int main() {
   for (const auto& i : buildList()) {
       const auto& id{ &i - RANGE_BEGIN};
   }
}  

Is there a way to point to the beginning of the range without declaring the vector outside of the for loop?

CodePudding user response:

Is there a way to point to the beginning of the range without declaring the vector outside of the for loop?

No, there is not. You must save it to a local variable in order to refer to it inside the loop body, eg:

int main() {
   auto theList = buildList();
   for (const auto& i : theList) {
       const auto& id{ &i - &theList[0] };
       ...
   }
}

But, since this code is simply calculating id to be an index into the vector, you may as well just use a separate local variable to track the index while iterating the vector with a range-for loop, eg:

int main() {
   size_t id = 0;
   for (const auto& i : buildList()) {
       // use id as needed...
         id;
   }
}

Otherwise, just use a traditional index-based for loop instead of a range-for loop, eg:

int main() {
   auto theList = buildList();
   for (size_t id = 0; id < theList.size();   id) {
       const auto& i = theList[id];
       ...
   }
}
  •  Tags:  
  • c
  • Related