Fyodor Menshikov
Fyodor Menshikov

Reputation: 191

Is it guaranteed that v.begin() + v.size() == v.end() for C++ vector v?

I try to insert value into C++ vector v before i-th element (or after element (i-1)). The code is very simple

v.insert(v.begin() + i, value);

I am sure that this statement works when i is between 0 inclusively and v.size() exclusively. Also, I believe that when i is strictly greater than v.size() or negative, the statement has undefined behaviour. But what if i == v.size()? Is v.begin() + i a valid iterator then? Is it guaranteed that v.begin() + v.size() == v.end()?

If it is guaranteed, could you reference the exact parts of the Standard? Also, if the guarantees change between standard versions, it would be useful to know these changes.

Without these guarantees I probably should use the following code:

if (i == v.size()) {
    v.insert(v.end(), value); // or just v.push_back(value);
} else {
    v.insert(v.begin() + i, value);
}

But it would be more succinct to use just one line as in the beginning of this question. In practice, the code from the beginning of this question works, but I want to be sure that it works everywhere. I tried to search the Standard but could not find this property of a random access iterator.

Upvotes: 2

Views: 3164

Answers (1)

Slava
Slava

Reputation: 44268

As stated on documentation

pos - iterator before which the content will be inserted. pos may be the end() iterator

so yes you can use end(). As for your another question:

Is it guaranteed that v.begin() + v.size() == v.end()?

yes it is, otherwise this loop:

for( auto it = vec.begin(); it != vec.end(); ++it ) ...

would not work properly as it must execute ++it exactly vec.size() times.

Upvotes: 5

Related Questions