C++vectorクリア要素の3つの方法

4186 ワード

#include 
#include 

using namespace std;

//STL vector       (  )  

void test()
{
    vector<int> vecnum;
    vecnum.push_back(1);
    vecnum.push_back(2);
    vecnum.push_back(3);
    vecnum.push_back(4);
    vecnum.push_back(5);
    vecnum.push_back(6);
    vecnum.push_back(7);

    //  vector      
    cout << "old: size = " << vecnum.size() << " ; capacity = " << vecnum.capacity() << endl;

    //1. clear(),    ,      

    //vecnum.clear();

    //2.    erase    ,    

    //vector::iterator it;
    //for (it = vecnum.begin(); it != vecnum.end(); )
    //{
    //    //    erase()   ,       ++
    //    it = vecnum.erase(it);
    //}

    //  :erase      ,          1,            ,  vector           

    //3.       swap,         
    //3.1    

    //vector().swap(vecnum);

    //3.2    
    vecnum.swap(vector<int>());

    //  vector      
    cout << "last: size = " << vecnum.size() << " ; capacity = " << vecnum.capacity() << endl;

}

int main()
{
    test();
    getchar();
    return 0;
}

 
転載先:https://www.cnblogs.com/zhanggaofeng/p/9338681.html