Std :: vector the difference in behavior between msvc and gcc on the operator [] after the reserve, what is correct?

This piece of code fails using msvc (due to a related error), but seems to work just fine with both gcc and clang. What is the correct behavior?

#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; } 
+5
source share
2 answers

The behavior is undefined. reserve saves only memory, but does not affect the size of the container. Perhaps you wanted to use resize ?

 std::vector<int> v; v.resize(10); for (int i = 0; i < 10; ++i) { v[i] = i * 2; } 

although in this case you could write

 std::vector<int> v(10); for (int i = 0; i < 10; ++i) { v[i] = i * 2; } 

Alternatively, you can use reserve conjunction with push_back :

 std::vector<int> v; v.reserve(10); for (int i = 0; i < 10; ++i) { v.push_back(i * 2); } 
+7
source

Some explanation for being undefined here:

 std::vector<int> v; v.reserve(10); 

reserve only "reserves" memory, but does not actually resize the vector. Therefore when you do

 v[i] = i * 2; 

You write int to a place that has not yet been initialized, since the vector is 0 in size.

What happens in such cases: undefined . Compilers and library implementations are free to do what they like here.

However, it is determined that the size for the vector does not change to reserve (but to resize ), but capacity (something else).

+3
source

Source: https://habr.com/ru/post/1258888/


All Articles