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.
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.
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.
For non-empty vectors yes, size()-1
is the index of the last element.