欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++容器——vector的reserve()和resize()踩坑记录

程序员文章站 2022-03-21 20:33:44
...

调bug搞了一晚上,发现坑在resize函数上。搜了一下相关的资料,做一下粗略的总结:

  • reserve:预留容器capacity,但不改变size(不初始化);
  • resize:改变size(不改变容器原有元素,新增size部分初始化);
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    vector<string> vecScore;
    vecScore.reserve(1);
    vecScore.push_back("test");
    vector<string>::iterator iter = vecScore.begin();
    while(iter != vecScore.end())
    {
        cout << *iter << endl;
        ++iter;
    }
    cout << "vector size after reserve: "<< vecScore.size() << endl;
    
    vecScore.resize(2);
    vector<string>::iterator iter1 = vecScore.begin();
    while(iter1 != vecScore.end())
    {
        cout << *iter1 << endl;
        ++iter1;
    }
    cout << "vector size after resize: "<< vecScore.size() << endl;
    
    vecScore.reserve(3);
    vector<string>::iterator iter2 = vecScore.begin();
    while(iter2 != vecScore.end())
    {
        cout << *iter2 << endl;
        ++iter2;
    }
    cout << "vector size after reserve again: "<< vecScore.size() << endl;

	return 0;
}

输出结果:
C++容器——vector的reserve()和resize()踩坑记录
另外,vector初始化时:

vector<string> vecScore(1); 
//等效于
//vector<string> vecScore;
//vecScore.push_back("");

参考:
https://www.cnblogs.com/zhuruibi/p/8983192.html
https://blog.csdn.net/jinx_qixianzhi/article/details/83143748
http://www.cplusplus.com/reference/vector/vector/resize/

相关标签: 计算机