2

Suppose I have a vector of some other container type. While iterating over the vector I change the size of the containers. Given that vectors try to remain contiguous in system memory, could the pointer arithmetic fail in loops like this? For example,

#include <stdlib.h>
#include <vector>

using namespace std;

int main(){
  vector<vector<double> > vec_vec(4);
  for (auto i=vec_vec.begin(); i!=vec_vec.end(); ++i){
    for (double j=0; j<100; j+=1.0){
      i->push_back(j)
    };
  };

  return 0;
}

I've had no issues using code like this so far, but now I'm wondering if I just got lucky. Is this safe? Does it depend on the kind of container used inside the vector?

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
user27118
  • 147
  • 4

3 Answers3

4

That's perfectly OK, you are not changing the outer vector. However there is no guarantee that all vectors will be contiguous in the memory. Each individual inner one will be, but don't expect that they are arranged one after the other in memory.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • What's wrong with the for loop? It's not iterating over the vector, it's generating data to store into it. – Daniel Jour Sep 21 '15 at 18:04
  • @DanielJour loops with `doubles` are in generally bad, due to floating point errors. – vsoftco Sep 21 '15 at 18:05
  • 1
    As long as you don't try to compare equality in the loop condition this use of the loop is perfectly valid, suppose a step size of 1.5 would be needed. – Daniel Jour Sep 21 '15 at 18:06
  • 2
    @DanielJour OK, I agree in this case, and removed the comment, however in OPs case, assuming the step is 1, should use an `int`, it will be automatically converted to `double` in the assignment. – vsoftco Sep 21 '15 at 18:09
2

You are modifying the contents of the std::vector you are iterating over. No the vector you are iterating over. They are different things.

First one is safe. Second one wouldn't be safe due to eventual memory reallocations.

jbgs
  • 2,795
  • 2
  • 21
  • 28
0

A vector is a fixed size management object (size,reserved, pointer) with its contiguous memory pointed to by pointer.

Thus you are not changing object's size

mksteve
  • 12,614
  • 3
  • 28
  • 50