C++ STL入门教程(1) vector向量容器使用方法

时间:2022-01-31 04:14:31

一、简介

Vectors 包含着一系列连续存储的元素,其行为和数组类似。

访问Vector中的任意元素或从末尾添加元素都可以在O(1)内完成,而查找特定值的元素所处的位置或是在Vector中插入元素则是O(N)。

C++ STL入门教程(1) vector向量容器使用方法

二、完整程序代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*请务必运行以下程序后对照阅读*/
 
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdexcept>
using namespace std;
 
void print(int num)
{
 cout << num << " ";
}
 
int main()
{
 //1. 初始化
 vector<int> v;
 vector<int>::iterator iv;
 
 v.reserve(100);//设置vector最小的元素容纳数量
 v.assign(10, 2);//将10个值为2的元素赋到vector中
 cout << v.capacity() << endl; //返回vector所能容纳的元素数量(在不重新分配内存的情况下)
 cout << v.size() << endl; //返回Vector实际含有的元素数量
 cout << endl;
 
 //2. 添加
 //注意:push_front()只适用于list和deque容器类型
 for (int i = 0; i < 10; i++)
 v.push_back(i);
 for_each(v.begin(), v.end(), print);//需要#include <algorithm>
 cout << endl;
 cout << v.size() << endl;
 cout << endl;
 
 //3. 插入及遍历、逆遍历
 v.insert(v.begin() + 3, 99);
 v.insert(v.end() - 3, 99);
 for_each(v.begin(), v.end(), print);
 cout << endl;
 for_each(v.rbegin(), v.rend(), print);//在逆序迭代器上做++运算将指向容器中的前一个元素
 cout << endl;
 
 //一般遍历写法
 for(iv = v.begin(); iv != v.end(); ++iv)
 cout << *iv << " ";
 cout << endl;
 cout << endl;
 
 //4. 删除
 v.erase(v.begin() + 3);
 for_each(v.begin(), v.end(), print);
 cout << endl;
 v.insert(v.begin() + 3, 99);//还原
 
 v.erase(v.begin(), v.begin() + 3); //注意删除了3个元素而不是4个
 for_each(v.begin(), v.end(), print);
 cout << endl;
 
 //注意:pop_front()只适用于list和deque容器类型
 v.pop_back();
 for_each(v.begin(), v.end(), print);
 cout << endl;
 cout << endl;
 
 //5. 查询
 cout << v.front() << endl;
 cout << v.back() << endl;
 
 //危险的做法,但一般我们就像访问数组那样操作就行
 for (int i = 15; i < 25; i++)
 cout << "Element " << i << " is " << v[i] << endl;
 //安全的做法
 int i;
 try
 {
 for (i = 15; i < 25; i++)
  cout << "Element " << i << " is " << v.at(i) << endl;
 }
 catch (out_of_range err)//#include <stdexcept>
 {
 cout << "out_of_range at " << i << endl;
 }
 cout << endl;
 
 //6. 清空
 v.clear();
 cout << v.size() << endl;//0
 for_each(v.begin(), v.end(), print); //已经clear,v.begin()==v.end(),不会有任何结果。
 
 return 0;
}

三、补充

vector应该说是在STL中使用最广泛的容器。大家知道,数组是几乎每一种语言都拥有的底层数据结构,但在我们的工作中,我们会大量的使用数组来表示同一类事物的一个集合。而vector实质上就是一个可以存储任何元素的动态数组。

vector虽然不是一个低级的数据结构,但是它各个操作的效率几乎是和数组相同的。只是它会使用比普通数组更多的空间。因为在vector因为空间不足而需要重新分配空间的时候,它一般会分配更多的空间(可能是当前size的1.5倍,这个是由具体实现定义的),以免每次插入一个新的元素的时候,都会重新分配空间。

重新分配空间是vector里面最没有效率的操作,所以在使用vector的时候要尽量避免重新分配空间。具体的方法是根据自己的实际需要来设定vector的capacity大小。

关于vector与list的详细比较,请参考这篇文章

参考网站:http://www.cplusplus.com/reference/vector/vector/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/synapse7/article/details/9749277