vector中resize()和reserve()
程序员文章站
2022-03-21 20:33:32
...
Mark一下:
1.resize(n)和resize(n, t), 调整vector数组的大小,多减少补,后面的t是初始化数值,添加时会调用一次构造函数,如果n的大小大于容器的话,容器的内存分配器将自动重新分配内存,如果内存分配失败,会报错 bad_alloc 。
例子:(来自c++官方文档)
// resizing vector
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector;
// set some initial content:
for (int i=1;i<10;i++) myvector.push_back(i);
myvector.resize(5);
myvector.resize(8,100);
myvector.resize(12);
std::cout << "myvector contains:";
for (int i=0;i<myvector.size();i++)
std::cout << ' ' << myvector[i];
std::cout << '\n';
return 0;
}
结果:
myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0 |
下面是使用实例:
// vector::reserve
#include <iostream>
#include <vector>
int main ()
{
std::vector<int>::size_type sz;
std::vector<int> foo;
sz = foo.capacity();
std::cout << "making foo grow:\n";
for (int i=0; i<100; ++i) {
foo.push_back(i);
if (sz!=foo.capacity()) {
sz = foo.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
std::vector<int> bar;
sz = bar.capacity();
bar.reserve(100); // this is the only difference with foo above
std::cout << "making bar grow:\n";
for (int i=0; i<100; ++i) {
bar.push_back(i);
if (sz!=bar.capacity()) {
sz = bar.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
return 0;
}
结果:
making foo grow: capacity changed: 1 capacity changed: 2 capacity changed: 4 capacity changed: 8 capacity changed: 16 capacity changed: 32 capacity changed: 64 capacity changed: 128 making bar grow: capacity changed: 100
【你必须非常努力 才能看起来毫不费力】
上一篇: JSTL (fn函数)