声明后在C++向量中分配元素

Sha*_*fiz 5 c++ resize vector dynamic

请参阅下面的代码和评论:

vector<int> v1(10);
cin>>v1[0]; // allowed
cin>>v1[1]; // allowed

// now I want v1 to hold 20 elements so the following is possible:

cin>>v1[15]>>v[19]; // how to resize the v1 so index 10 to 19 is available.
Run Code Online (Sandbox Code Playgroud)

Aar*_*ron 6

您只需在添加新值之前调整向量的大小:

v1.resize(20);
Run Code Online (Sandbox Code Playgroud)

  • @Gunner:是的 - 调整大小后,您可以通过 v1[19] 访问 v1[0],而无需 push_back。 (2认同)