If I have a standard C++ container std::vector<Bar>
and I shrink it by calling .resize()
with a size smaller than the current .size()
, in which order are the extra elements destroyed?
(Implementation choices are interesting if you can find two implementations which differ.)
(This was inspired by a comment from James Kanze.)
The January 2012 working draft contains the C++11 standard plus minor editorial changes.
Source, working draft
For vector
:
void resize(size_type sz);
Effects: Ifsz <= size()
, equivalent toerase(begin() + sz, end());
. Ifsize() < sz
, appendssz - size()
value-initialized elements to the sequence.
vector::erase
does not specify the order of removal. I would expect it to be in order from begin() + sz
to end()
, because that makes sense to me, but that is just my expectation. I can't find anything about it in the standard.
The implementation of vector
distributed with Visual Studio 2013 does appear to indeed erase in that order, as does MinGW's g++ 4.8.1 as well as g++ 4.7.3 (not MinGW). These are the compilers I happen to have easy access to.
In the same standard, for list
:
void resize(size_type sz);
1 Effects: Ifsize() < sz
, appendssz - size()
value-initialized elements to the sequence. Ifsz <= size()
, equivalent to
list<T>::iterator it = begin();
advance(it, sz);
erase(it, end());
and
void resize(size_type sz, const T& c);
Effects:
if (sz > size())
insert(end(), sz-size(), c);
else if (sz < size()) {
iterator i = begin();
advance(i, sz);
erase(i, end());
}
else
; // do nothing
It then goes on to specify absolutely nothing useful about ordering for list::erase
.
The implementation of list
distributed with Visual Studio 2013 does appear to erase in reverse order, while MinGW's g++ 4.8.1 and g++ 4.7.3 (not MinGW) do not.
Working draft
For vector
void resize(size_type sz);
Effects: Ifsz <= size()
, equivalent to callingpop_back()
size() - sz
times. Ifsize() < sz
, appendssz - size()
default-inserted elements to the sequence.
This indicates that elements are removed in reverse order.
For list
:
void resize(size_type sz);
1 Effects: Ifsize() < sz
, appendssz - size()
value-initialized elements to the sequence. Ifsz <= size()
, equivalent to
list<T>::iterator it = begin();
advance(it, sz);
erase(it, end());
and
void resize(size_type sz, const T& c);
Effects:
if (sz > size())
insert(end(), sz-size(), c);
else if (sz < size()) {
iterator i = begin();
advance(i, sz);
erase(i, end());
}
else
; // do nothing
It then goes on to specify absolutely nothing useful about ordering for list::erase
.
For deque
the standard specifies the same behavior as for vector
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With