vector之resize剖析

一、先看下面一段代码

vector<int> tempVector;
    tempVector.resize(5);
    tempVector.push_back(1);
    tempVector.push_back(2);
    tempVector.push_back(3);
    tempVector.push_back(4);
    tempVector.push_back(5);
    for(auto iter:tempVector)
    {
        cout << iter << endl;
    }

上面的结果输出是什么?1,2,3,4,5?如果你觉得是,那恭喜你答错了。请继续往下看

二、测试结果:
vector之resize剖析
看到了吧,使用resize后,直接把vector中的元素初始化成了0。
那问题来了:怎么能使用resize,然后又能输出1,2,3,4,5?答案在下面的测试代码。

三、测试代码:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> tempVector;
    tempVector.resize(5);
    tempVector.push_back(1);
    tempVector.push_back(2);
    tempVector.push_back(3);
    tempVector.push_back(4);
    tempVector.push_back(5);
    for(auto iter:tempVector)
    {
        cout << iter << endl;
    }

    cout << "=====after clear====" << endl;
    tempVector.clear();
    tempVector.push_back(1);
    tempVector.push_back(2);
    tempVector.push_back(3);
    tempVector.push_back(4);
    tempVector.push_back(5);

    for(auto iter:tempVector)
    {
        cout << iter << endl;
    }

    system("pause");
    return 0;
}

测试结果:
vector之resize剖析
resize之后,使用clear函数清空一下就可以了。

总结:曾经我以为我学会了使用vector,到后来我才发现我还是没有用好用准用会。
更多vector剖析请参考:https://blog.****.net/toby54king/article/details/86737201