Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
}
like image 414
cmourglia Avatar asked Oct 27 '16 12:10

cmourglia


People also ask

Does Reserve change vector size?

reserve() does not change the size of the vector.

Is std :: vector slower than array?

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.

What does vector Reserve do?

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.

Does vector Reserve allocate memory?

vector::reserve does allocate memory, so your question about reserving memory without allocating is incorrect.


1 Answers

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);
}
like image 191
krzaq Avatar answered Sep 20 '22 09:09

krzaq