Zouch - 9 months ago 42
C++ Question

# std::vector difference of behaviour between msvc and gcc on operator[] after reserve, which is right?

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;
}


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);
}