Numerous questions/answers inform me that std::vector<T>::resize(n)
will increase capacity and size, whilst std::vector<T>::reserve(n)
only increases capacity.
One example is Choice between vector::resize() and vector::reserve().
A comment in that question indicates that after use of reserve(n)
, the use of
vec[i less than n] = ..
is undefined behaviour, and many examples given are claimed to lead to segfaults.
When I compile and run
#include <vector>
#include <iostream>
void f(const std::vector<double> &s) {
std::cout << "s.size() = " << s.size() << std::endl;
std::cout << "s.capacity() = " << s.capacity() << std::endl;
}
int main() {
std::size_t n = 20121;
std::vector<double> a;
a.reserve(2*n);
a[n] = 2.5;
std::cout << "a["<<n<<"] = " << a[n] << std::endl;
f(a);
std::vector<double> b;
b.resize(2*n);
b[n] = 2.5;
std::cout << "b["<<n<<"] = " << b[n] << std::endl;
f(b);
}
my output is
a[20121] = 2.5
s.size() = 0
s.capacity() = 40242
b[20121] = 2.5
s.size() = 40242
s.capacity() = 40242
Questions:
Has there been a change that makes this ok? Is this just my compiler (g++ v5.2.0
) giving me undefined, but nice, behaviour?
As a second point of curiosity, why does f(a)
tell me the size is 0 (guessed answer: no push_back
calls), even though a[n]
returns a valid value?