C++ Vector用法详解

2020-01-06 13:16:13王冬梅

结果:

复制代码
clear before: 1    2    3    
clear before capacity:4
after clear: 
after clear capacity:4
为什么这里打印的capacity()的结果是4不做详细解释,请参考上面关于capacity的介绍。 通过结果,我们可以看到clear()之后数据全部清除了,但是capacity()依旧是4。

 

假设:我们通过原本的vector来创建一个新的vector,让我们看看将会发生什么?

复制代码
//
//  vector.cpp
//  vector
//
//  Created by scandy_yuan on 13-1-7.
//  Copyright (c) 2013年 Sam. All rights reserved.
//

 

#include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[])
{

    // insert code here...
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    cout << "v.capacity()" << v.capacity() << endl;
    
    vector<int> v1(v);
    cout << "v1.capacity()" << v1.capacity() << endl;
    return 0;
}

 

结果:

复制代码
v.capacity()4
v1.capacity()3
可以看出,v1的capacity()是v的实际大小,因此可以达到压缩vector的目的。但是我们不想新建一个,我们想在原本的vector(即v)上进行压缩,那么借鉴上面的方式思考另一种方式。

 

假设:我们通过swap函数把v1交换回v,看看会发生什么?

复制代码
//
//  vector.cpp
//  vector
//
//  Created by scandy_yuan on 13-1-7.
//  Copyright (c) 2013年 Sam. All rights reserved.
//

 

#include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[])
{

    // insert code here...
    vector<int> v;