在STL容器中vector用的还是比较多的,但是在使用时,会对resize()和reserve()的使用产生迷惑,现在就对这一情况做个对比:
resize():改变的是size()与capacity()的大小
(1)、比原来的变小之后,后面的会被截断
(2)、比原来的变大之后,后面的会被填充新的东西,不同的编译器可能会不同。也可以自己指定后面填充的内容
reserve():改变的只是capacity()的大小,size()和内容不会改变
#include <math.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>using namespace std;int main()
{vector<int> v1{1, 2, 3, 4, 5};std::cout << "v1 source data is : " << "\n";for (auto &v : v1){std::cout << v << ", ";}std::cout << "\n" << " v1.size=" << v1.size() << " v1.capacity=" << v1.capacity() << endl;std::cout << "after resize to 2" << endl;v1.resize(2); //尺寸由5改变为2,多余字符被截掉了,只剩下hefor (auto &v : v1){std::cout << v << ", ";}std::cout << " v1.size=" << v1.size() << " v1.capacity=" << v1.capacity() << endl;std::cout << "after resize to 12" << endl;v1.resize(12, 10000); //尺寸由2改变为12, 后面的数据被填充了10个0for (auto &v : v1){std::cout << v << ", ";}std::cout << "\n" << " v1.size=" << v1.size() << " v1.capacity=" << v1.capacity() << endl;std::cout << "\n";std::cout << "===================================================================" << endl;std::cout << "\n";vector<int> v2{1, 2, 3, 4, 5};std::cout << "v2 source data is : " << "\n";for (auto &v : v2){std::cout << v << ", ";}std::cout << "\n" << " v2.size=" << v2.size() << " v2.capacity=" << v2.capacity() << endl;std::cout << "after reserve to 2" << endl;v1.reserve(2); // size-内容不变,capacity()可能会变化for (auto &v : v2){std::cout << v << ", ";}std::cout << "\n" << " v2.size=" << v2.size() << " v2.capacity=" << v2.capacity() << endl;std::cout << "after reserve to 12" << endl;v1.reserve(12); //size-内容不变,capacity()可能会变化for (auto &v : v2){std::cout << v << ", ";}std::cout << "\n" << " v2.size=" << v2.size() << " v2.capacity=" << v2.capacity() << endl;return 0;
}
运行结果:
根据上篇文章std::string的resize()与reserve()的区别和本篇文章的练习,总结如下:
STL中的容器-vector、string来说(不包括set/map,因为这2个没有resize()与reserve()接口):
resize():改变的是size()与capacity()的大小
(1)、比原来的变小之后,后面的会被截断
(2)、比原来的变大之后,后面的会被填充新的东西,不同的编译器可能会不同
reserve():改变的只是capacity()的大小,内容不会改变