1

Say I have a std::vector named myVec.

I don't know the exact size it will reach, so i use only myVec.push_back(...).

Can I rely on the fact that after I have pushed_back, size()-1 will give me the index of that last element? Thanks.

G.Rassovsky
  • 774
  • 1
  • 10
  • 23

2 Answers2

5

You have two separate questions. In the title you ask:

Does std::vector size()-1 ALWAYS give the index of the last element?

No. It does not give the index of the last element if the vector is empty.

Can I rely on the fact that after I have pushed_back, size()-1 will give me the index of that last element?

Yes, if the vector is not empty, then size() - 1 is guaranteed to be the index of the last element.

  • Yes, thanks for pointing that out... I meant only on non-empty vectors and after push_backs, but I can see how the question can be misleading. – G.Rassovsky Jul 24 '14 at 10:00
4

For non-empty vectors yes, size()-1 is the index of the last element.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
  • @arturn Not sure what is your point. After calling `resize(100)` the vector size is 100, and its last index is 99, which is also `size() - 1`. – Wojtek Surowka Oct 15 '22 at 21:23
  • @arturn In C++ null normally means null pointer, or 0 character ending C-style strings. Here we have a vector of int8_t, so talking about nulls may be misleading. The vector after resize will have all elements of the default value zero. – Wojtek Surowka Oct 17 '22 at 12:43