c++ - 删除一个/多个元素后 vector 数组是否会调整大小?

标签 c++ function vector size erase

是否 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/

相关文章:

c++ - 字符串迭代器不兼容 boost::tokenizer

c++ - 将数据移入函数然后返回到它的来源时是否存在任何未定义的行为问题?

javascript - 将函数转换为 JSON,然后再次运行

c++ - 这个 std::vector 和 std::shared_ptr 内存泄漏是一个错误吗?

c++ - boost::dynamic_bitset 如何存储位

c++ - 您听说过 C++ 服务器页面吗?

javascript - 窗口滚动只调用一次 JS 函数

function - 传递值时与通过引用传递时 map 的奇怪突变(Golang)

c++ - 如何遍历二维 vector ?

C++ "terminating with uncaught exception of type std::out_of_range: vector"合并排序算法中的错误