0

Please excuse me if my understanding isn't up to par yet, Im still learning C++, and Im coming from an interpreted language (R).

My question is regarding the usage of vectors as index containers for range based for loops, In the following example :

//Declare 
std::vector<int> a{5,1,6,9} ;
std::vector<int> b{0,3} ;

//Reserve Memory
a.reserve(100) ;

//Loop & Modify
for(int i : b){
         a.push_back(a[i] + 400) ;
}

My question is, can this result in undefined behavior in some way?

dvd280
  • 876
  • 6
  • 11

1 Answers1

1

As long as b contains valid indexes into a your code is perfectly fine.

A problem would arise if you would modify the container your iterating over with range for, e.g. this would be invalid:

for (auto e : a)
{
    a.push_back(...);
}

But you are not doing this so you are OK.

bolov
  • 72,283
  • 15
  • 145
  • 224