向量数组在擦除 one/more 元素后是否会调整大小?
Does a vector array resize after erasing one/more elements?
是否 vector.erase
调整矢量对象的大小,以便我可以使用 vector.size()
测量缩小后的大小?
例如;
vector<int> v(5);
v = {1,2,3,4,5};
我想删除 4 个;
v.erase(v.begin()+4);
我的矢量对象 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.
是否 vector.erase
调整矢量对象的大小,以便我可以使用 vector.size()
测量缩小后的大小?
例如;
vector<int> v(5);
v = {1,2,3,4,5};
我想删除 4 个;
v.erase(v.begin()+4);
我的矢量对象 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.