std::vector resize() 函数
void resize (size_type n, value_type val = value_type());
Resizes the container so that it contains n elements.
- If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying
them).- If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a
size of n. If val is specified, the new elements are initialized as
copies of val, otherwise, they are value-initialized.- If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.
Notice that this function changes the actual content of the container
by inserting or erasing elements from it.
改变容器的大小使他包含n个元素。
如果n小于当前容器大小,则内容减少到前n个元素,移除后面的元素。
如果n大于当前容器大小,则在后面插入一些元素至n个大小,如果val被定义,则插入val的复制,否则插入默认值0。
如果n大于当前容器的容量capacity,则自动进行内容重新分配。
使用resize时,
如果n大于capacity,则会重新分配地址空间;n小于capacity,则仍旧使用原先的空间
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "test\n";
std::vector<int> tt;
tt.reserve(20);
for (int i=0; i<10; ++i) {
tt[i] = i;
}
std::cout << "原始地址: " << &tt[0] << std::endl;
tt.resize(15);
std::cout << "resize后(n < capacity): " << &tt[0] << std::endl;
tt.resize(30);
std::cout << "resize后(n > capacity): " << &tt[0] << std::endl;
return 0;
}
结果:
原始地址: 0x1318e80
resize后(n < capacity): 0x1318e80
resize后(n > capacity): 0x1318ee0