为什么这样说:
cout << values[0] << " " << values[1] << " " << values[2] << endl;
显示
1 2 3
尽管使用了 pop back 从 vector 中删除最后一个元素。这些值不应该也被删除吗?还是即使删除了元素, vector 也会调整大小?
示例代码如下:
// 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;
}
最佳答案
“值”和“元素”是一回事。 pop_back()
如果 vector 不为空,则从 vector 中删除最后一个值。
vector
的设计使得程序员有责任不越界访问 vector。如果一个 vector 有 2 个元素并且您尝试通过 at()
以外的任何方法访问第三个元素,您会导致 undefined behaviour .
要进行边界检查,请使用 values.at(0)
而不是 values[0]
等,并包含一个 try
...catch
block 以捕获生成的异常。
关于c++ - 使用 vector 时,pop_back 是否会连同元素一起删除值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32577576/