C++模板库之Vector

vector支持随机访问,所以只要你知道元素的位置,你就可以在常量时间里访问任何一个元素。如果是在末端添加或者删除元素,那么它的效果是非常好的,但是如何是在前端或者中段添加或删除元素,那么它的效率就不怎么样了。

vector的容量是至关重要的,因为一旦重新分配内存,vector元素相关的reference,pointer,iterator都会失效,此外,重新分配内存非常耗时间。我们可以通过reserve()保留适当容量,避免重新分配内存。但是,不能通过reserve()缩减容量。既然vector的容量不会缩减,那么,reference,pointer,iterator也会继续有效,继续指向动作前发生的位置。若要缩减容量,可以使用函数 v.shrink_to_fit()。

看一下vector的实例,

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
    vector<string> sentence;
    sentence.reserve(5);
    
    sentence.push_back("Hello, ");
    sentence.insert(sentence.end(),{"how","are","you","?"});

    copy(sentence.cbegin(),sentence.cend(),ostream_iterator<string>(cout," "));

    cout << endl;

    cout << "max_size(): " << sentence.max_size() << endl;
    cout << "size(): " << sentence.size() << endl;
    cout << "capacity(): " << sentence.capacity() << endl;

    swap(sentence[1],sentence[3]);
    sentence.insert(find(sentence.begin(),sentence.end(),"?"),"always");

    sentence.back() = "!";
    copy(sentence.cbegin(),sentence.cend(),ostream_iterator<string>(cout," "));
    cout << endl;
    
    cout << "size(): " << sentence.size() << endl;
    cout << "capacity(): " << sentence.capacity() << endl;

    sentence.pop_back();
    sentence.pop_back();
    
    sentence.shrink_to_fit();

    cout << "size(): " << sentence.size() << endl;
    cout << "capacity(): " << sentence.capacity() << endl;
}

以上程序运行结果:

Hello, how are you?
max_size(): 1073741823
size(): 5
capacity(): 5

Hello, you are how always!
size(): 6
capacity(): 10
size(): 4
capacity(): 4

max_size()和capacity()的输出由现实决定。

猜你喜欢

转载自blog.csdn.net/LEO_ANDERSON/article/details/81168471