This snippet of code fails miserably using msvc (out of bound error) but appears to work fine with both gcc and clang. What is the correct behaviour ?
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.reserve(10);
for (int i = 0; i < 10; ++i)
{
v[i] = i * 2;
}
for (int i = 0; i < 10; ++i)
{
std::cout << v[i] << " ";
}
std::cout << std::endl;
return 0;
}
reserve() does not change the size of the vector.
A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.
vector::reserve() vector reserve() indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory. Begin Declare a variable v of vector type. Declare another variable it as iterator of vector type.
vector::reserve does allocate memory, so your question about reserving memory without allocating is incorrect.
The behavior is undefined. reserve
only reserves memory, but doesn't affect the size of the container. Maybe you wanted to use resize
?
std::vector<int> v;
v.resize(10);
for (int i = 0; i < 10; ++i)
{
v[i] = i * 2;
}
though in this case you could've written
std::vector<int> v(10);
for (int i = 0; i < 10; ++i)
{
v[i] = i * 2;
}
Alternatively, you could use reserve
in concert with push_back
:
std::vector<int> v;
v.reserve(10);
for (int i = 0; i < 10; ++i)
{
v.push_back(i * 2);
}
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