C++ Vector用法详解

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

    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;
    
    v.swap(v1);
    cout << "v.swap(v1).capacity()" << v.capacity() << endl;
    return 0;
}

 

结果:

复制代码
v.capacity()4
v1.capacity()3
v.swap(v1).capacity()3
可以看出,v.capacity()变成了3,目的达到。但是代码给人感觉繁琐臃肿,我们从新考虑一种新的写法,采用匿名对象来代替v1这个中间对象:vector<int> (v).swap(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;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    cout << "v.capacity()" << v.capacity() << endl;
    
    vector<int> (v).swap(v);
    cout << "v.capacity()" << v.capacity() << endl;
    return 0;
}

 

结果:

复制代码
v.capacity()4
v.capacity()3
可以看到 v.capacity()由4编程了3,目的达到。

 

之前没有关注C++11,感谢@egmkang,确实在C++11中已经提供了shrink_to_fit()函数实现vector的压缩。

如下:

复制代码
#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v;