I think I didn't understand the initialization of std::vector
.
The code below seems to compile and run fine with gcc, clang, and MSVC.
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{{}};
v[10] = 11; // if initialize with v{}, segmentation fault.
std::cout << "v[10]:" << v[10] << std::endl; // prints v[10]:11
for (auto e : v) // prints only v[x]:0
std::cout << "v[x]:" << e << std::endl;
}
// result:
// v[10]:11
// v[x]:0
Is accessing the element with v[10]
causing an undefined behavior?
Why does the above code with v{{}}
run fine, but not with v{}
?
Edit) Originally I didn't use the correct terminology, my fault. When I said 'not compiled', I was trying to say 'not run(after compile)'.