2

Let's say I have a 2d vector of ints and I push_back a bunch of objects into one of the middle internal vectors. Do I risk iterator/reference invalidation?

std::vector<std::vector<int>> ints2d;

for (int i = 0; i < 10; ++i)
{
     ints2d.push_back(std::vector<int>());
     ints2d[i].resize(10,0);
}

//later during some runtime event

for (int i = 0, i < 100; ++i)
{
    ints2d[3].push_back(8);
}

//are my references at risk of being invalid now?
ggorlen
  • 44,755
  • 7
  • 76
  • 106

2 Answers2

3

You have (potentially) invalidated references to the vector you are pushing to (the one at the index 3 of ints2d). All other references remain valid.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
0

Your question is easily answered by reading a bit of documentation. Basically, as mentioned in the previous link, "If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.".

Of course only references/iterators into the vector you are actually doing push_back on are potentially invalidated. The containing container is not affected.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • Only the size of the vector that was pushed to changed. – ruohola Sep 06 '19 at 18:08
  • So this doesn't answer the question at all. – ruohola Sep 06 '19 at 18:11
  • @ruohola Yes it does. The question was "Lets say I have a 2d vector of ints and I push_back a bunch of objects into one of the middle internal vectors do I risk iterator/reference invalidation." - And yes you do, for the vector pushed into. Which should be clear by the documentation I linked and quoted. Of course there's no invalidation of the *containing* vector, but that's not what's being modified, so that should be obvious. – Jesper Juhl Sep 06 '19 at 18:15
  • It's *very* obvious that the question is exactly about invalidating iterators to the vectors or the containing vector. – ruohola Sep 06 '19 at 18:25
  • @ruohola Maybe obvious to you. Not obvious to me. But regardless, I think the answer I provided answers the question. You may disagree - which is fine, that's what votes are for. – Jesper Juhl Sep 06 '19 at 18:39