为什么这个声明:
cout << values[0] << " " << values[1] << " " << values[2] << endl;
Run Code Online (Sandbox Code Playgroud)
显示
1 2 3
即使使用pop back来移除向量中的最后一个元素.不应该删除这些值吗?或者即使元素被删除,矢量也会调整大小?
以下是示例代码:
// This program demonstrates the vector pop_back member function.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> values;
// Store values in the vector.
values.push_back(1); // Last element in values is 1
values.push_back(2); // Now elements in values are 1,2
values.push_back(3); // Now elements in values are 1,2,3
cout << "The size of values is " << values.size() << endl; // values has 3 elements
// Remove a value from the vector.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl; // 1 is Removed thus size is 2
cout << values[0] << " " << values[1] << " " << values[2] << endl;
// Now remove another value from the vector.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
cout << values[0] << " " << values[1] << " " << values[2] << endl;
// Remove the last value from the vector.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
cout << values[0] << " " << values[1] << " " << values[2] << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8442 次 |
| 最近记录: |