How reserve in std::vector works + Accessing vector with []
问题 Why vector[n] = val doesn't give segmentation fault or changes the vector data, right before reserving an empty vector. Check this example: #include <iostream> #include <vector> int main() { std::vector<int> temp; temp.reserve(8); temp[0] = 1; temp[3] = 3; //why no attribution??? temp[7] = 1; temp[8] = 3; //why no segmentation fault??? std::cout << temp.size(); for(auto&a: temp){ //because the attribution didn't work, no loop needed std::cout << a; } return 0; } Also, why the operator []