C++STL学习(1)容器vector

注:博客内容均来自于对《C++标准库》侯捷,华中科技大学出版社一书的笔记。转载请注明出处。所有例程在Red Hat Linux 3.2.2-5版本上编译运行g++的版本是 g++ (GCC) 3.2.2 20030222

vector可以理解成一个动态数组,vector的结构可以用下图来理解。
vector的结构
vector的元素之间总是存在着某种顺序,所以vector是一种有序群集。 vector支持随机存储。可以在常数时间内存取任何一个元素
vector的特点
vector的容量非常重要,因为:
1、一旦内存重新配置,和vector元素相关的所有references,pointers,iterators都会失效;
2、内存重新配置很耗时间。

-一、vector的操作函数

1.1构造、拷贝和析构
C++STL学习(1)容器vector_第1张图片
1.2读取相关
C++STL学习(1)容器vector_第2张图片
1.3赋值
C++STL学习(1)容器vector_第3张图片
1.4取元素
C++STL学习(1)容器vector_第4张图片
1.5迭代器
C++STL学习(1)容器vector_第5张图片
1.6安插,移除相关
C++STL学习(1)容器vector_第6张图片

-二,例子

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;

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

    copy(vt.begin(), vt.end(),
        std::ostream_iterator<string>(cout, " "));
    cout<<endl;
    cout<< "max_size() :" << vt.max_size() << endl;
    cout<< "size() :" << vt.size() << endl;
    cout<< "capacity() :" << vt.capacity() << endl;

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

    vt.back() = "!";

    copy(vt.begin(), vt.end(),
        std::ostream_iterator<string>(cout, " "));
    cout<<endl;
    cout<< "max_size() :" << vt.max_size() << endl;
    cout<< "size() :" << vt.size() << endl;
    cout<< "capacity() :" << vt.capacity() << endl;

}

在g++中编译并运行。使用g++版本为:
C++STL学习(1)容器vector_第7张图片
运行结果
C++STL学习(1)容器vector_第8张图片

注:博客内容均来自于对《C++标准库》侯捷,华中科技大学出版社一书的笔记。转载请注明出处。

你可能感兴趣的:(C++,vector)