void resize (size_type n);
void resize (size_type n, const value_type& val);
调整容器大小,使其包含n个元素。
1,如果n小于等于当前容器大小,则容器缩小为前n个元素,删除后面的元素。
#include <vector>
#include <stdio.h>
#include <algorithm>
int main()
{
std::vector<int> test;
test.push_back(1);
test.push_back(11);
test.push_back(12);
test.push_back(13);
test.resize(2); //容器大小没变,元素减少了
printf("test.capacity = %lu, size = %lu\n", test.capacity(), test.size()); //capacity = 4, size = 0
for(unsigned int i = 0; i < test.size(); i++)
{
printf("%d\n", test.at(i));
}
return 0;
}
2,如果n大于当前容器大小(会引起内存重新分配),则容器扩展内容,在容器的末尾插入足够多的元素以达到n的大小。如果指定了val,则将新元素初始化为val的副本,否则,则对新元素进行值初始化。
#include <vector>
#include <stdio.h>
#include <algorithm>
int main()
{
std::vector<int> test;
test.push_back(1);
test.push_back(11);
test.push_back(12);
test.push_back(13);
test.resize(6); //容器大小改变
printf("test.capacity = %lu, size = %lu\n", test.capacity(), test.size()); //capacity = 4, size = 0
for(unsigned int i = 0; i < test.size(); i++)
{
printf("%d\n", test.at(i));
}
return 0;
}
void reserve (size_type n);
调用容器大小,至少足够容纳n个元素。
如果n大于当前vector容器的容量,该函数将导致容器重新分配存储空间,将容量增加到n(或更大)。在所有其他情况下,函数调用不会导致重新分配,vector容量也不会受到影响。
#include <vector>
#include <stdio.h>
#include <algorithm>
int main()
{
std::vector<int> test;
test.push_back(1);
test.push_back(11);
test.push_back(12);
test.push_back(13);
test.reserve(2); //
printf("test.capacity = %lu, size = %lu\n", test.capacity(), test.size()); //capacity = 4, size = 0
for(unsigned int i = 0; i < test.size(); i++)
{
printf("%d\n", test.at(i));
}
return 0;
}
#include <vector>
#include <stdio.h>
#include <algorithm>
int main()
{
std::vector<int> test;
test.push_back(1);
test.push_back(11);
test.push_back(12);
test.push_back(13);
test.reserve(12); //
printf("test.capacity = %lu, size = %lu\n", test.capacity(), test.size()); //capacity = 4, size = 0
for(unsigned int i = 0; i < test.size(); i++)
{
printf("%d\n", test.at(i));
}
return 0;
}
容量扩大,元素不变。