是否 vector.erase
调整 vector 对象的大小,以便我可以使用 vector.size()
测量缩小后的大小?
例如;
vector<int> v(5);
v = {1,2,3,4,5};
我想删除 4 by;
v.erase(v.begin()+4);
我的 vector 对象是否
v
现在有 4 个大小。换句话说是v.size() == 4
这次手术后?
最佳答案
是的,尺寸 减少 当你删除元素时。
不要害怕通过编写一个最小的示例来测试自己,就像这样:):
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v(5);
v = {1,2,3,4,5};
cout << v.size() << endl;
v.erase(v.begin()+4);
cout << v.size() << endl;
return 0;
}
你会得到:
gsamaras@gsamaras-A15:~$ g++ -Wall -std=c++0x main.cpp
gsamaras@gsamaras-A15:~$ ./a.out
5
4
我们会期待吗?我的意思是ref说:
Return size
Returns the number of elements in the vector.
This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.
关于c++ - 删除一个/多个元素后 vector 数组是否会调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817532/