STL容器之vector

时间:2023-03-10 04:20:03
STL容器之vector

【1】模板类vector

模板类vector可理解为广义数组。广义数组,即与类型无关的数组,具有与数组相同的所有操作。

那么,你或许要问:既然C++语言本身已提供了一个序列式容器array,为什么还要vector呢?

我们一直强调,事物总是朝向更先进的方向螺旋式发展与进化。这个问题其中的道理也不例外。

vector的数据安排及操作方式与array非常相似。两者唯一区别在于空间运用的灵活性。

array是静态空间,一旦配置不能改变。要想换个大(或小)点的房子,一切琐细得由客户端自己料理(步骤如下):

首先,配置一块新空间,然后从旧地址将元素逐一搬往新地址,最后把原来的空间释放还给系统。

vector是动态空间,不仅可以在运行期再确定容器容量大小,而且随着元素的加入,它的内部机制会自动扩充空间以容纳新元素。

所以,相比较array,运用vector对内存的合理灵活性利用有很大的帮助。

【2】vector应用实例

(1)有构造函数才会有容器。模板类vector的构造函数及构建实例。代码如下:

 #include <iostream>
#include <vector>
#include <memory>
using namespace std; void main()
{
/* C++11
default (1)
explicit vector (const allocator_type& alloc = allocator_type());
// 构建一个空容器(默认构造函数)。 fill (2)
explicit vector (size_type n);
vector (size_type n, const value_type& val,
const allocator_type& alloc = allocator_type());
// 构建一个容器。容器存储n个元素,每个元素的初始值为val(如果提供)。 range (3)
template <class InputIterator>
vector (InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type());
// 构建一个容器。容器存储元素与源容器中[first,last)区间的元素内容一样。
// 内容指存放元素的值及位置和[first,last)区间中完全一样,方向也要一致。 copy (4)
vector (const vector& x);
vector (const vector& x, const allocator_type& alloc);
// 拷贝构造函数。构建一个容器,逐个复制源容器x中的每一个元素,存放到本容器中,方向也保持一致。 move (5)
vector (vector&& x);
vector (vector&& x, const allocator_type& alloc);
// 移动构造函数。如果新的分配器alloc和x的分配器alloc不一样,那么将移动源容器x里面的元素到新的vector。
// 如果分配器是一样的,那么将直接转换其所有权。
// 将右值引用中容器x所有元素的所有权移动到新的vector中,避免付出昂贵的复制代价。 initializer list (6)
vector (initializer_list<value_type> il,
const allocator_type& alloc = allocator_type());
// 初始化列表构造函数。从初始化列表il中复制每一个元素,放到新的vector中,方向与列表保持一致。
*/
// default (1)
vector<int> vInt1; // fill (2)
int n;
cin >> n;
vector<int> vInt2(n); vector<int> vInt3(); vector<int> vInt4(, ); // range(3)
vector<int> vInt5(vInt4.begin(), vInt4.end()); int myInt[] = {, , , , };
vector<int> vInt6(myInt, myInt + sizeof(myInt) / sizeof(int)); // copy(4)
vector<int> vInt7(vInt4); // move(5)
vector<unique_ptr<string> > vUS = vector<unique_ptr<string> >({
unique_ptr<string> (new string("Qin")),
unique_ptr<string> (new string("Liu")),
unique_ptr<string> (new string("Wang")),
unique_ptr<string> (new string("Zhang"))}); // initializer_list(6)
vector<int> vInt8({, , , , });
}

对于任何一个类而言,构造函数是相当重要的,其所有对象呈现的操作方法都与构造函数息息相关。

类的构造函数为对象先天性的行为铺垫(比如:类的构造函数若多一个参数,那么类将会有很多成员方法为这个参数服务)。

下面的实例演示使用vector模板方便创建动态分配数组的优势(内置数组无法完成)

 #include <iostream>
#include <vector>
#include <string>
using namespace std; void main()
{
cout << "请输入预处理学生数目:\n";
int nStudents;
cin >> nStudents;
vector<string> names(nStudents);
vector<int> scores(nStudents);
cout << "请输入" << nStudents << " 个学生的姓名和英语成绩 (0 ~ 100)。\n";
int i;
for (i = ; i < nStudents; ++i)
{
cout << "姓名 No" << i + << ": ";
cin >> names[i];
cout << "成绩 (0 ~ 100):";
cin >> scores[i];
cin.get();
}
cout << "输入所有学生信息结束。\n";
cout << "打印输入姓名及成绩如下:\n";
for (i = ; i < nStudents; ++i)
{
cout << names[i] << "\t" << scores[i] << endl;
} cin.get();
}
// Run out:
/*
请输入预处理学生数目:
5
请输入5 个学生的姓名和英语成绩 (0 ~ 100)。
姓名 No1: sun
成绩 (0 ~ 100):89
姓名 No2: li
成绩 (0 ~ 100):87
姓名 No3: wang
成绩 (0 ~ 100):90
姓名 No4: qin
成绩 (0 ~ 100):98
姓名 No5: zhang
成绩 (0 ~ 100):69
输入所有学生信息结束。
打印输入姓名及成绩如下:
sun 89
li 87
wang 90
qin 98
zhang 69
*/

vector模板更多的方法请看下节。

(2)常用成员方法应用示例如下代码:

 #include <iostream>
#include <vector>
using namespace std; void printVectorValue(vector<int> & vInt)
{
for (vector<int>::iterator pt = vInt.begin(); pt != vInt.end(); ++pt)
{
cout << *pt << "\t";
}
cout << endl;
} void main()
{
// vector对象的常用方法以及应用示例如下:
cout << "动态构建一个整型容器(请输入整数值,0时退出):\n";
vector<int> vMyInts;
int nTemp;
while (cin >> nTemp && nTemp != )
{
vMyInts.push_back(nTemp);
}
cout << "您输入 " << vMyInts.size() << "个元素,分别如下: " << endl;
printVectorValue(vMyInts);
cout << "构建整型容器vMyInts完成" << endl << endl; //(1)a.assign(b.begin(), b.begin() + 3); // b为向量,将b的0~2个元素构成的向量赋给a
cout << "(1) assign方法 :" << endl;
vector<int> vA1;
vA1.assign(vMyInts.begin(), vMyInts.begin() + );
cout << "容器vA1元素如下:" << endl;
printVectorValue(vA1);
cout << "(1) assign方法应用示例完成。" << endl << endl; //(2)a.assign(4, 2); // 容器a只含4个元素,且每个元素值为2
cout << "(2) assign(4, 2)方法 :" << endl;
vector<int> vA2;
vA2.assign(, );
cout << "容器vA2元素如下:" << endl;
printVectorValue(vA2);
cout << "(2) assign(4, 2)方法应用示例完成。" << endl << endl; //(3)a.back(); // 返回容器a的最后一个元素
cout << "(3) back方法 :" << endl;
cout << "vMyInts容器的最后一个元素是:" << vMyInts.back() << endl;
cout << "(3) back方法应用示例完成。" << endl << endl; // (4)a.front(); // 返回容器a的第一个元素
cout << "(4) front方法 :" << endl;
cout << "vMyInts容器的最前一个元素是:" << vMyInts.front() << endl;
cout << "(4) front方法应用示例完成。" << endl << endl; // (5)a[i]; // 返回a的第i个元素,当且仅当a[i]存在
cout << "(5) a[i] 方法 :" << endl;
cout << "vMyInts容器的第2个元素是:" << vMyInts[ - ] << endl;
cout << "(5) a[i]方法应用示例完成。" << endl << endl; // (6)a.clear(); // 清空容器a中的元素
cout << "(6) clear() 方法 :" << endl;
cout << "清空前,vA2容器中的元素为: " << endl;
printVectorValue(vA2);
vA2.clear();
cout << "清空后,vA2容器中的元素为: " << endl;
printVectorValue(vA2);
cout << "(6) clear()方法应用示例完成。" << endl << endl; // (7)a.empty(); // 判断容器a是否为空,空则返回ture,不空则返回false
cout << "(7) empty() 方法 :" << endl;
cout << "vA2容器是否为空:" << vA2.empty() << endl;
cout << "(7) empty()方法应用示例完成。" << endl << endl; // (8)a.pop_back(); // 删除容器a的最后一个元素
cout << "(8) pop_back() 方法 :" << endl; vA2.clear();
cout << "删除前,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
vMyInts.pop_back();
cout << "删除最后一个元素后,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
cout << "(8) pop_back()方法应用示例完成。" << endl << endl; // (9)a.erase(a.begin() + 1, a.begin() + 3);
// 删除容器a中第1个(从第0个算起)到第2个元素,也就是说删除的元素从[a.begin() + 1, a.begin() + 3)(前闭后开区间)
cout << "(9) erase() 方法 :" << endl; vA2.clear();
cout << "删除前,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
vMyInts.erase(vMyInts.begin() + , vMyInts.begin() + );
cout << "删除后,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
cout << "(9) erase()方法应用示例完成。" << endl << endl; // (10)a.push_back(5); // 在容器a的最后一个向量后插入一个元素,其值为5
cout << "(10) push_back() 方法 :" << endl; vA2.clear();
cout << "添加前,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
vMyInts.push_back();
cout << "添加后,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
cout << "(10) push_back()方法应用示例完成。" << endl << endl; // (11)a.insert(a.begin() + 1, 5);
// 在容器a的第1个元素(从第0个算起)的位置插入数值5,如a为1,2,3,4 插入元素后为1,5,2,3,4
cout << "(11) insert() 方法 :" << endl;
cout << "插入前,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
vMyInts.insert(vMyInts.begin() + , );
cout << "插入后,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
cout << "(11) insert()方法应用示例完成。" << endl << endl; // (12)a.insert(a.begin() + 1, 3, 5); // 在容器a的第1个元素(从第0个算起)的位置插入3个数,其值都为5
cout << "(12) insert() 方法 :" << endl;
cout << "插入前,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
vMyInts.insert(vMyInts.begin() + , , );
cout << "插入后,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
cout << "(12) insert()方法应用示例完成。" << endl << endl; // (13)a.insert(a.begin() + 1, b + 3, b + 6);
// b为数组。在a的第1个元素(从第0个算起)的位置插入b的第3个元素到第5个元素(不包括b + 6)
// b为1,2,3,4,5,9,8 插入元素后为1,4,5,9,2,3,4,5,9,8
cout << "(13) insert() 方法 (容器示例):" << endl;
cout << "插入前,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
cout << "插入前,vA1容器中的元素为: " << endl;
printVectorValue(vA1);
vA1.insert(vA1.begin() + , vMyInts.begin() + , vMyInts.begin() + );
cout << "插入后,vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
cout << "插入后,vA1容器中的元素为: " << endl;
printVectorValue(vA1);
cout << "(13) insert()方法应用示例完成。" << endl << endl; cout << "(13) insert() 方法 (数组示例):" << endl;
cout << "插入前,vA1容器中的元素为: " << endl;
printVectorValue(vA1);
cout << "数组中的元素为: {1, 2, 3, 4, 5, 6}" << endl;
int nArrB[] = {, , , , , };
vA1.insert(vA1.begin() + , nArrB + , nArrB + );
cout << "插入后,vA1容器中的元素为: " << endl;
printVectorValue(vA1);
cout << "(13) insert()方法应用示例完成。" << endl << endl; // (14)a.size(); // 返回容器a中元素的个数;
cout << "(14) size() 方法: " << endl;
cout << "vA1容器中的元素为: " << endl;
printVectorValue(vA1);
cout << "vA1容器中元素个数为:" << vA1.size() << endl;
cout << "(14) size()方法应用示例完成。" << endl << endl; // (15)a.capacity(); // 返回容器a的容量
cout << "(15) capacity() 方法: " << endl;
cout << "vA1容器的容量为:" << vA1.capacity() << endl;
cout << "(15) capacity()方法应用示例完成。" << endl << endl; // (16)a.rezize(10); // 将a的现有元素个数调至10个,多则删,少则补,其值随机
cout << "(16) resize() 方法: " << endl;
cout << "重新分配大小前,vA1容器中元素为: " << endl;
printVectorValue(vA1);
vA1.resize();
cout << "vA1.resize(6) 重新分配大小后,vA1容器中元素为:" << endl;
printVectorValue(vA1);
cout << "(16) resize()方法应用示例完成。" << endl << endl; // (17)a.rezize(10, 2); // 将容器a的现有元素个数调至10个,多则删,少则补其值为2
cout << "(17) resize() 方法: " << endl;
cout << "重新分配大小前,vA1容器中元素为: " << endl;
printVectorValue(vA1);
vA1.resize(, );
cout << "vA1.resize(10, 110) 重新分配大小后,vA1容器中元素为:" << endl;
printVectorValue(vA1);
cout << "(17) resize()方法应用示例完成。" << endl << endl; // (18)a.reserve(100);
// 将容器a的容量(capacity)扩充至100,也就是说现在测试 a.capacity();的时候返回值是100。
// 这种操作只有在需要给a添加大量数据的时候才有意义,
// 因为这将避免内存多次容量扩充操作(当a的容量不足时电脑会自动扩容,当然这必然降低性能。)
cout << "(18) reserve() 方法: " << endl;
cout << "扩容前,vA1容器的容量为:" << vA1.capacity() << endl;
vA1.reserve();
cout << "扩容后,vA1容器的容量为:" << vA1.capacity() << endl;
cout << "(18) reserve()方法应用示例完成。" << endl << endl; // (19)a.swap(b); // b为容器,将a中的元素和b中的元素进行整体性交换
cout << "(19) swap() 方法: " << endl;
cout << "vA1容器中的元素为: " << endl;
printVectorValue(vA1);
cout << "vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
vA1.resize();
vMyInts.resize();
vA1.swap(vMyInts);
cout << "vA1容器中的元素为: " << endl;
printVectorValue(vA1);
cout << "vMyInts容器中的元素为: " << endl;
printVectorValue(vMyInts);
cout << "(19) swap() 方法应用示例完成。 " << endl << endl; // (20)a = b; // b为容器,将一个对象赋给另一个对象
cout << "(20) 赋值方法: " << endl;
cout << "vA1容器中的元素为: " << endl;
printVectorValue(vA1);
vector<int> vTemp = vA1;
cout << " vTemp = vA1 后,vTemp 容器中的元素为: " << endl;
printVectorValue(vTemp);
cout << "(20) 赋值方法应用示例完成。 " << endl << endl; // (20)a == b; // b为容器,向量的比较操作还有!=,>=,<=,>,<
cout << "(21) 比较操作: " << endl;
cout << "vA1容器中的元素为: " << endl;
printVectorValue(vA1);
cout << " vTemp 容器中的元素为: " << endl;
printVectorValue(vTemp);
cout << "vA1 == vTemp 比较:" << (vA1 == vTemp) << endl;
cout << "(21) 比较操作应用示例完成。 " << endl << endl;
cin >> nTemp;
}
// Run out
/*
动态构建一个整型容器(请输入整数值,0时退出):
12
23
34
45
56
67
78
89
90
0
您输入 9个元素,分别如下:
12 23 34 45 56 67 78 89 90
构建整型容器vMyInts完成 (1) assign方法 :
容器vA1元素如下:
12 23 34
(1) assign方法应用示例完成。 (2) assign(4, 2)方法 :
容器vA2元素如下:
12 12 12 12
(2) assign(4, 2)方法应用示例完成。 (3) back方法 :
vMyInts容器的最后一个元素是:90
(3) back方法应用示例完成。 (4) front方法 :
vMyInts容器的最前一个元素是:12
(4) front方法应用示例完成。 (5) a[i] 方法 :
vMyInts容器的第2个元素是:23
(5) a[i]方法应用示例完成。 (6) clear() 方法 :
清空前,vA2容器中的元素为:
12 12 12 12
清空后,vA2容器中的元素为: (6) clear()方法应用示例完成。 (7) empty() 方法 :
vA2容器是否为空:1
(7) empty()方法应用示例完成。 (8) pop_back() 方法 :
删除前,vMyInts容器中的元素为:
12 23 34 45 56 67 78 89 90
删除最后一个元素后,vMyInts容器中的元素为:
12 23 34 45 56 67 78 89
(8) pop_back()方法应用示例完成。 (9) erase() 方法 :
删除前,vMyInts容器中的元素为:
12 23 34 45 56 67 78 89
删除后,vMyInts容器中的元素为:
12 45 56 67 78 89
(9) erase()方法应用示例完成。 (10) push_back() 方法 :
添加前,vMyInts容器中的元素为:
12 45 56 67 78 89
添加后,vMyInts容器中的元素为:
12 45 56 67 78 89 99
(10) push_back()方法应用示例完成。 (11) insert() 方法 :
插入前,vMyInts容器中的元素为:
12 45 56 67 78 89 99
插入后,vMyInts容器中的元素为:
12 11 45 56 67 78 89 99
(11) insert()方法应用示例完成。 (12) insert() 方法 :
插入前,vMyInts容器中的元素为:
12 11 45 56 67 78 89 99
插入后,vMyInts容器中的元素为:
12 12 12 11 45 56 67 78 89 99 (12) insert()方法应用示例完成。 (13) insert() 方法 (容器示例):
插入前,vMyInts容器中的元素为:
12 12 12 11 45 56 67 78 89 99 插入前,vA1容器中的元素为:
12 23 34
插入后,vMyInts容器中的元素为:
12 12 12 11 45 56 67 78 89 99 插入后,vA1容器中的元素为:
12 11 45 56 23 34
(13) insert()方法应用示例完成。 (13) insert() 方法 (数组示例):
插入前,vA1容器中的元素为:
12 11 45 56 23 34
数组中的元素为: {1, 2, 3, 4, 5, 6}
插入后,vA1容器中的元素为:
12 2 3 4 11 45 56 23 34
(13) insert()方法应用示例完成。 (14) size() 方法:
vA1容器中的元素为:
12 2 3 4 11 45 56 23 34
vA1容器中元素个数为:9
(14) size()方法应用示例完成。 (15) capacity() 方法:
vA1容器的容量为:9
(15) capacity()方法应用示例完成。 (16) resize() 方法:
重新分配大小前,vA1容器中元素为:
12 2 3 4 11 45 56 23 34
vA1.resize(6) 重新分配大小后,vA1容器中元素为:
12 2 3 4 11 45
(16) resize()方法应用示例完成。 (17) resize() 方法:
重新分配大小前,vA1容器中元素为:
12 2 3 4 11 45
vA1.resize(10, 110) 重新分配大小后,vA1容器中元素为:
12 2 3 4 11 45 100 100 100 100 (17) resize()方法应用示例完成。 (18) reserve() 方法:
扩容前,vA1容器的容量为:13
扩容后,vA1容器的容量为:30
(18) reserve()方法应用示例完成。 (19) swap() 方法:
vA1容器中的元素为:
12 2 3 4 11 45 100 100 100 100 vMyInts容器中的元素为:
12 12 12 11 45 56 67 78 89 99 vA1容器中的元素为:
12 12 12 11 45
vMyInts容器中的元素为:
12 2 3 4 11
(19) swap() 方法应用示例完成。 (20) 赋值方法:
vA1容器中的元素为:
12 12 12 11 45
vTemp = vA1 后,vTemp 容器中的元素为:
12 12 12 11 45
(20) 赋值方法应用示例完成。 (21) 比较操作:
vA1容器中的元素为:
12 12 12 11 45
vTemp 容器中的元素为:
12 12 12 11 45
vA1 == vTemp 比较:1
(21) 比较操作应用示例完成。
*/

类的成员方法应用示例运行结果如下:

STL容器之vector

这么多成员方法,为什么没有sort排序方法呢?

(3)通用成员函数。上面常用方法那么多,怎么没有排序方法呢?这点得追溯于STL的设计理念(尽可能一劳永逸)。

STL从更广泛的角度定义了非成员函数来执行这些操作,即不是为每个类都定义sort()成员函数,而是定义一个适用于所有容器类的非成员函数sort()。

试想一个问题,假设有10个类,每个类都支持10种操作,若每个类都有自己的成员函数,则需要定义100(10*10)个成员函数。而采用STL方式,只需要定义10个非成员函数即可。

另外需要注意,已有执行相同任务的非成员函数,STL有时还会为类定义一个成员函数,因为对于有些操作来说,类特定算法的效率比通用算法高。

下面学习几个所谓的公用函数:for_each()、random_shuffle()、sort()。

  3.1 for_each函数接受3个参数,前两个是定义容器中区间的迭代器,最后一个是指向函数的指针。可以用for_each函数来代替for循环。例如:

 #include <iostream>
#include <vector>
#include <algorithm> // for_each
using namespace std; void printVectorValue(int & rInt)
{
cout << rInt << "\t";
} void main()
{
cout << "动态构建一个整型容器(请输入整数值,0时退出):\n";
vector<int> vMyInts;
int nTemp;
while (cin >> nTemp && nTemp != )
{
vMyInts.push_back(nTemp);
}
cout << "您输入 " << vMyInts.size() << " 个元素,分别如下: " << endl;
cout << "使用for循环打印容器元素如下:" << endl;
for (vector<int>::iterator pIt = vMyInts.begin(); pIt != vMyInts.end(); ++pIt)
{
cout << *pIt << "\t";
}
cout << endl << "使用for_each打印容器元素如下:" << endl;
for_each(vMyInts.begin(), vMyInts.end(), printVectorValue);
cout << endl << "构建整型容器vMyInts完成" << endl << endl;
cin >> nTemp;
}
// Run out
/*
动态构建一个整型容器(请输入整数值,0时退出):
12
23
34
45
56
67
78
89
90
0
您输入 9 个元素,分别如下:
使用for循环打印容器元素如下:
12 23 34 45 56 67 78 89 90
使用for_each打印容器元素如下:
12 23 34 45 56 67 78 89 90
构建整型容器vMyInts完成
*/

  这样可以避免显式使用迭代器变量。

  3.2 random_shffle函数接受两个指定区间的迭代器参数,并随机排列该区间中的元素。应用示例代码如下:

 #include <iostream>
#include <vector>
#include <string>
#include <algorithm> // for_each
using namespace std; template<class T>
void printVectorValue(T & rInt)
{
cout << rInt << "\t";
} void main()
{
cout << "动态构建一个整型容器(请输入整数值,0时退出):\n";
vector<int> vMyInts;
int nTemp;
while (cin >> nTemp && nTemp != )
{
vMyInts.push_back(nTemp);
}
cout << "您输入 " << vMyInts.size() << " 个元素,分别如下: " << endl;
cout << "使用for_each打印排序前容器元素如下:" << endl;
for_each(vMyInts.begin(), vMyInts.end(), printVectorValue<int>);
random_shuffle(vMyInts.begin(), vMyInts.end());
cout << endl << "使用for_each打印排序后容器元素如下:" << endl;
for_each(vMyInts.begin(), vMyInts.end(), printVectorValue<int>); cout << endl;
vector<string> vStr;
vStr.push_back("sun");
vStr.push_back("zhang");
vStr.push_back("huang");
vStr.push_back("liu");
vStr.push_back("qin");
cout << endl << "打印排序前容器元素如下:" << endl;
for (int j = ; j < vStr.size(); ++j)
{
cout << vStr[j].c_str() << "\t";
}
std::random_shuffle(vStr.begin(), vStr.end()); // 迭代器
cout << endl << "打印排序后容器元素如下:" << endl;
for (int j = ; j < vStr.size(); ++j)
{
cout << vStr[j].c_str() << "\t";
}
cout << endl;
system("pause");
}

  程序运行结果如下:

STL容器之vector

  3.3 sort函数也要求容器支持随机访问,该函数有两个版本:

  第一个版本接受两个定义区间的迭代器参数,并使用为存储在容器中的类型元素定义的<运算符。

  备注:如果元素为用户自定义类型,必须定义能够处理该类型对象的operator<()函数),对区间中的元素进行操作。

  第二个版本接受3个参数,前两个参数也是指定区间的迭代器,最后一个参数是指向要使用的函数的指针(而不是比较的operator<()运算符)。

  sort函数的应用示例代码如下:

 #include <iostream>
#include <vector>
#include <string>
#include <algorithm> // for_each
using namespace std; template<class T>
void printVectorValue(T & rInt)
{
cout << rInt << "\t";
} struct student
{
string strName;
int nAge; student(string sName = "liu", int nAge = ) : strName(sName), nAge(nAge)
{}
}; bool worseThan(const student & stuObject1, const student & stuObject2)
{
if (stuObject1.nAge > stuObject2.nAge)
{
return true;
}
else if (stuObject1.nAge == stuObject2.nAge
&& stuObject1.strName > stuObject2.strName)
{
return true;
}
else
{
return false;
}
} void printValue(const student & rStuObject)
{
cout << rStuObject.strName << " " << rStuObject.nAge << "\n";
} void main()
{
cout << "sort函数版本1测试程序:" << endl;
cout << "动态构建一个整型容器(请输入整数值,0时退出):\n";
vector<int> vMyInts;
int nTemp;
while (cin >> nTemp && nTemp != )
{
vMyInts.push_back(nTemp);
}
cout << "您输入 " << vMyInts.size() << " 个元素,分别如下: " << endl;
cout << "使用for_each打印排序前容器元素如下:" << endl;
for_each(vMyInts.begin(), vMyInts.end(), printVectorValue<int>);
sort(vMyInts.begin(), vMyInts.end()); // 版本1
cout << endl << "使用for_each打印排序后容器元素如下:" << endl;
for_each(vMyInts.begin(), vMyInts.end(), printVectorValue<int>); cout << endl << endl << "sort函数版本2测试程序:" << endl;
vector<student> vStudents;
vStudents.push_back(student("sun", ));
vStudents.push_back(student("zhang", ));
vStudents.push_back(student("huang", ));
vStudents.push_back(student("liu", ));
vStudents.push_back(student("qin", ));
cout << "使用for_each打印排序前容器元素如下:" << endl;
for_each(vStudents.begin(), vStudents.end(), printValue);
sort(vStudents.begin(), vStudents.end(), worseThan); // 版本2
cout << "使用for_each打印排序后容器元素如下:" << endl;
for_each(vStudents.begin(), vStudents.end(), printValue);
cout << endl;
system("pause");
}

  程序运行结果如下:

STL容器之vector

  通用非成员函数结束。

【3】学习《STL源码剖析》中vector

  (1)vector容器可以自动扩充内存空间,具体的扩充规则测试代码如下:

 #include <vector>
#include <iostream>
#include <algorithm>
using namespace std; template<class T>
void printVectorValue(T & rInt)
{
cout << rInt << " ";
} template<class T>
void printSizeAndCapacity(vector<T> & oVec)
{
for_each(oVec.begin(), oVec.end(), printVectorValue<T>);
cout << endl << "size = " << oVec.size() << endl;
cout << "capacity = " << oVec.capacity() << endl << endl;
} int main()
{
vector<int> iv(, );
printSizeAndCapacity(iv);
for (int i = ; i < ; ++i)
{
iv.push_back(i + );
printSizeAndCapacity<int>(iv);
} system("pause");
}

  vector容器示意图如下:

STL容器之vector

  运行结果如下:

STL容器之vector

  有一个遗留问题:如size不为零时,扩充后容量应该是之前的2倍,根据上例实际情况,不应该有奇数值的容量!求再探索,作此备录。

  (2)vector迭代器和数据结构,如下图所示:

STL容器之vector

  (3)vector部分源码如下:

 #include<iostream>
#include<memory.h>
using namespace std; // alloc是SGI STL的空间配置器
template <class T, class Alloc = alloc>
class vector
{
public:
// vector的嵌套类型定义,typedefs用于提供iterator_traits<I>支持
typedef T value_type;
typedef value_type* pointer;
typedef value_type* iterator;
typedef value_type& reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
protected:
// 这个提供STL标准的allocator接口
typedef simple_alloc <value_type, Alloc> data_allocator; iterator start; // 表示目前使用空间的头
iterator finish; // 表示目前使用空间的尾
iterator end_of_storage; // 表示实际分配内存空间的尾 void insert_aux(iterator position, const T& x); // 在position位置插入值为x的元素 // 释放分配的内存空间
void deallocate()
{
// 由于使用data_allocator进行内存空间的分配,
// 所以匹配使用data_allocator::deallocate()进行释放
// 如果直接释放, 对于data_allocator内部使用内存池的版本就会发生错误
if (start)
data_allocator::deallocate(start, end_of_storage - start);
} void fill_initialize(size_type n, const T& value)
{
start = allocate_and_fill(n, value);
finish = start + n; // 设置当前使用内存空间的结束点
// 构造阶段(不多分配内存)
// 所以要设置内存空间结束点(与已经使用的内存空间结束点相同)
end_of_storage = finish;
} public:
// 获取几种迭代器
iterator begin() { return start; }
iterator end() { return finish; } // 返回当前对象个数
size_type size() const { return size_type(end() - begin()); }
size_type max_size() const { return size_type(-) / sizeof(T); }
// 返回重新分配内存前最多能存储的对象个数
size_type capacity() const { return size_type(end_of_storage - begin()); }
// 判空
bool empty() const { return begin() == end(); }
// 重载[](下标访问)
reference operator[](size_type n) { return *(begin() + n); } // 默认构造函数。默认构造vector不分配内存空间
vector() : start(), finish(), end_of_storage() {} vector(size_type n, const T& value) { fill_initialize(n, value); }
vector(int n, const T& value) { fill_initialize(n, value); }
vector(long n, const T& value) { fill_initialize(n, value); } // 需要对象提供默认构造函数
explicit vector(size_type n) { fill_initialize(n, T()); } vector(const vector<T, Alloc>& x)
{
start = allocate_and_copy(x.end() - x.begin(), x.begin(), x.end());
finish = start + (x.end() - x.begin());
end_of_storage = finish;
} ~vector()
{
// 析构对象
destroy(start, finish);
// 释放内存
deallocate();
} vector<T, Alloc>& operator=(const vector<T, Alloc>& x); // 提供访问函数
reference front() { return *begin(); }
reference back() { return *(end() - ); } ////////////////////////////////////////////////////////////////////////////////
// 向容器尾追加一个元素, 可能导致内存重新分配(开辟新空间、移动原数据、释放原内存)
////////////////////////////////////////////////////////////////////////////////
// push_back(const T& x)
// |
// |---------------- 容量已满?
// |
// ----------------------------
// No | | Yes
// | |
// ↓ ↓
// construct(finish, x); insert_aux(end(), x);
// ++finish; |
// |------ 内存不足, 重新分配
// | 大小为原来的2倍
// new_finish = data_allocator::allocate(len); <stl_alloc.h>
// uninitialized_copy(start, position, new_start); <stl_uninitialized.h>
// construct(new_finish, x); <stl_construct.h>
// ++new_finish;
// uninitialized_copy(position, finish, new_finish); <stl_uninitialized.h>
//////////////////////////////////////////////////////////////////////////////// void push_back(const T& x)
{
// 内存满足条件则直接追加元素, 否则需要重新分配内存空间
if (finish != end_of_storage)
{
construct(finish, x);
++finish;
}
else
insert_aux(end(), x);
} ////////////////////////////////////////////////////////////////////////////////
// 在指定位置插入元素
////////////////////////////////////////////////////////////////////////////////
// insert(iterator position, const T& x)
// |
// |------------ 容量是否足够 && 是否是end()?
// |
// -------------------------------------------
// No | | Yes
// | |
// ↓ ↓
// insert_aux(position, x); construct(finish, x);
// | ++finish;
// |-------- 容量是否够用?
// |
// --------------------------------------------------
// Yes | | No
// | |
// ↓ |
// construct(finish, *(finish - 1)); |
// ++finish; |
// T x_copy = x; |
// copy_backward(position, finish - 2, finish - 1); |
// *position = x_copy; |
// ↓
// data_allocator::allocate(len); <stl_alloc.h>
// uninitialized_copy(start, position, new_start); <stl_uninitialized.h>
// construct(new_finish, x); <stl_construct.h>
// ++new_finish;
// uninitialized_copy(position, finish, new_finish); <stl_uninitialized.h>
// destroy(begin(), end()); <stl_construct.h>
// deallocate();
//////////////////////////////////////////////////////////////////////////////// iterator insert(iterator position, const T& x)
{
size_type n = position - begin();
if (finish != end_of_storage && position == end())
{
construct(finish, x);
++finish;
}
else
insert_aux(position, x);
return begin() + n;
} iterator insert(iterator position) { return insert(position, T()); } void pop_back()
{
--finish;
destroy(finish);
} iterator erase(iterator position)
{
if (position + != end())
copy(position + , finish, position);
--finish;
destroy(finish);
return position;
} iterator erase(iterator first, iterator last)
{
iterator i = copy(last, finish, first);
// 析构掉需要析构的元素
destroy(i, finish);
finish = finish - (last - first);
return first;
} // 调整size, 但是并不会重新分配内存空间
void resize(size_type new_size, const T& x)
{
if (new_size < size())
erase(begin() + new_size, end());
else
insert(end(), new_size - size(), x);
}
void resize(size_type new_size) { resize(new_size, T()); } void clear() { erase(begin(), end()); } protected:
// 分配空间, 并且复制对象到分配的空间处
iterator allocate_and_fill(size_type n, const T& x)
{
iterator result = data_allocator::allocate(n);
uninitialized_fill_n(result, n, x);
return result;
} // 提供插入操作
////////////////////////////////////////////////////////////////////////////////
// insert_aux(iterator position, const T& x)
// |
// |---------------- 容量是否足够?
// ↓
// -----------------------------------------
// Yes | | No
// | |
// ↓ |
// 从opsition开始, 整体向后移动一个位置 |
// construct(finish, *(finish - 1)); |
// ++finish; |
// T x_copy = x; |
// copy_backward(position, finish - 2, finish - 1); |
// *position = x_copy; |
// ↓
// data_allocator::allocate(len);
// uninitialized_copy(start, position, new_start);
// construct(new_finish, x);
// ++new_finish;
// uninitialized_copy(position, finish, new_finish);
// destroy(begin(), end());
// deallocate();
//////////////////////////////////////////////////////////////////////////////// template <class T, class Alloc>
void insert_aux(iterator position, const T& x)
{
if (finish != end_of_storage) // 还有备用空间
{
// 在备用空间起始处构造一个元素,并以vector最后一个元素值为其初值
construct(finish, *(finish - ));
++finish;
T x_copy = x;
copy_backward(position, finish - , finish - );
*position = x_copy;
}
else // 已无备用空间
{
const size_type old_size = size();
const size_type len = old_size != ? * old_size : ;
// 以上配置元素:如果大小为0,则配置1(个元素大小)
// 如果大小不为0,则配置原来大小的两倍
// 前半段用来放置原数据,后半段准备用来放置新数据 iterator new_start = data_allocator::allocate(len); // 实际配置
iterator new_finish = new_start;
// 将内存重新配置
try
{
// 将原vector的安插点以前的内容拷贝到新vector
new_finish = uninitialized_copy(start, position, new_start);
// 为新元素设定初值 x
construct(new_finish, x);
// 调整水位
++new_finish;
// 将安插点以后的原内容也拷贝过来
new_finish = uninitialized_copy(position, finish, new_finish);
}
catch(...)
{
// 回滚操作
destroy(new_start, new_finish);
data_allocator::deallocate(new_start, len);
throw;
}
// 析构并释放原vector
destroy(begin(), end());
deallocate(); // 调整迭代器,指向新vector
start = new_start;
finish = new_finish;
end_of_storage = new_start + len;
}
} ////////////////////////////////////////////////////////////////////////////////
// 在指定位置开始连续插入n个值为x的元素
////////////////////////////////////////////////////////////////////////////////
// insert(iterator position, size_type n, const T& x)
// |
// |---------------- 插入元素个数是否为0?
// ↓
// -----------------------------------------
// No | | Yes
// | |
// | ↓
// | return;
// |----------- 内存是否足够?
// |
// -------------------------------------------------
// Yes | | No
// | |
// |------ (finish - position) > n? |
// | 分别调整指针 |
// ↓ |
// ---------------------------- |
// No | | Yes |
// | | |
// ↓ ↓ |
// 插入操作, 调整指针 插入操作, 调整指针 |
// ↓
// data_allocator::allocate(len);
// new_finish = uninitialized_copy(start, position, new_start);
// new_finish = uninitialized_fill_n(new_finish, n, x);
// new_finish = uninitialized_copy(position, finish, new_finish);
// destroy(start, finish);
// deallocate();
//////////////////////////////////////////////////////////////////////////////// template <class T, class Alloc>
void insert(iterator position, size_type n, const T& x)
{
// 如果n为0,则不进行任何操作
if (n != )
{
if (size_type(end_of_storage - finish) >= n)
{ // 剩下的备用空间大于等于“新增元素的个数”
T x_copy = x;
// 以下计算插入点之后的现有元素个数
const size_type elems_after = finish - position;
iterator old_finish = finish;
if (elems_after > n)
{
// 插入点之后的现有元素个数 大于 新增元素个数
uninitialized_copy(finish - n, finish, finish);
finish += n; // 将vector 尾端标记后移
copy_backward(position, old_finish - n, old_finish);
fill(position, position + n, x_copy); // 从插入点开始填入新值
}
else
{
// 插入点之后的现有元素个数 小于等于 新增元素个数
uninitialized_fill_n(finish, n - elems_after, x_copy);
finish += n - elems_after;
uninitialized_copy(position, old_finish, finish);
finish += elems_after;
fill(position, old_finish, x_copy);
}
}
else
{ // 剩下的备用空间小于“新增元素个数”(那就必须配置额外的内存)
// 首先决定新长度:就长度的两倍 , 或旧长度+新增元素个数
const size_type old_size = size();
const size_type len = old_size + max(old_size, n);
// 以下配置新的vector空间
iterator new_start = data_allocator::allocate(len);
iterator new_finish = new_start;
__STL_TRY
{
// 以下首先将旧的vector的插入点之前的元素复制到新空间
new_finish = uninitialized_copy(start, position, new_start);
// 以下再将新增元素(初值皆为n)填入新空间
new_finish = uninitialized_fill_n(new_finish, n, x);
// 以下再将旧vector的插入点之后的元素复制到新空间
new_finish = uninitialized_copy(position, finish, new_finish);
}
# ifdef __STL_USE_EXCEPTIONS
catch(...)
{
destroy(new_start, new_finish);
data_allocator::deallocate(new_start, len);
throw;
}
# endif /* __STL_USE_EXCEPTIONS */
destroy(start, finish);
deallocate();
start = new_start;
finish = new_finish;
end_of_storage = new_start + len;
}
}
}
};

  (4)使用主要问题及成员函数详解。

    4.1 erase函数。vector::erase()方法有两种重载形式:

      (1.1)iterator erase (iterator _Where);

      (1.2)iterator erase (iterator _First, iterator _Last);

      如果是删除指定位置的元素时:返回值是一个迭代器,指向删除元素下一个元素。

      如果是删除某范围内的元素时:返回值也表示一个迭代器,指向最后一个删除元素的下一个元素。

      请看如下“临床典型性”应用错误示例代码:

 #include <vector>
#include <iostream>
#include <algorithm>
using namespace std; template<class T>
void printVectorValue(T & rInt)
{
cout << rInt << " ";
} void main()
{
vector <int> v1;
for (int i = ; i < ; ++i)
{
v1.push_back(i + );
}
cout << "(1) v1 容器元素如下:" << endl;
for_each(v1.begin(), v1.end(), printVectorValue<int>);
cout << endl; v1.erase(v1.begin( ));
cout << "(2) v1 容器元素如下:" << endl;
for_each(v1.begin(), v1.end(), printVectorValue<int>);
cout << endl; v1.erase(v1.begin( ) + , v1.begin( ) + );
cout << "(3) v1 容器元素如下:" << endl;
for_each(v1.begin(), v1.end(), printVectorValue<int>);
cout << endl; v1.push_back();
vector<int>::iterator itPt;
for (itPt = v1.begin(); itPt != v1.end(); ++itPt)
{
if ( == *itPt)
{
v1.erase(itPt);
}
} system("pause");
}

      程序运行结果如下:

STL容器之vector

      分析程序:一一遍历容器找到元素值为14,然后一一删除。程序为什么会崩溃呢?

      其实,出现这种原因是没搞懂erase的删除原理(套路),当调用erase()后迭代器就失效了,即变成一个野指针。

      所以要处理这种问题,关键是要解决调用erase()方法后,迭代器变成野指针的问题。

      结合套路,解决这个问题有两种方案:

      第一种:正向删除。

      第二种:逆向删除。代码如下:

 #include <vector>
#include <iostream>
#include <algorithm>
using namespace std; template<class T>
void printVectorValue(T & rInt)
{
cout << rInt << " ";
} // 正删
template<class T>
void eraseAll(vector<T> & v1, T value)
{
vector<T>::iterator itPt;
for (itPt = v1.begin(); itPt != v1.end();)
{
if (value == *itPt)
{
itPt = v1.erase(itPt);
}
else
{
++itPt;
}
}
} // 逆删
template<class T>
void eraseAll2(vector<T> & v1, T value)
{
vector<T>::iterator itPt;
for (itPt = --v1.end(); itPt != v1.begin();)
{
if (value == *itPt)
{
v1.erase(itPt--);
}
else
{
--itPt;
}
} if (value == *itPt)
{
v1.erase(itPt);
}
} void main()
{
vector<int> v1(, );
for (int i = ; i < ; ++i)
{
v1.push_back(i + );
}
cout << "(1) v1 容器元素如下:" << endl;
for_each(v1.begin(), v1.end(), printVectorValue<int>);
cout << endl; v1.erase(v1.begin( ));
cout << "(2) v1 容器元素如下:" << endl;
for_each(v1.begin(), v1.end(), printVectorValue<int>);
cout << endl; v1.erase(v1.begin( ) + , v1.begin( ) + );
cout << "(3) v1 容器元素如下:" << endl;
for_each(v1.begin(), v1.end(), printVectorValue<int>);
cout << endl; v1.insert(v1.begin() + , , );
v1.push_back();
v1.push_back();
cout << "(4) 删除前 v1 容器元素如下:" << endl;
for_each(v1.begin(), v1.end(), printVectorValue<int>);
cout << endl; // 第一种正向删除
eraseAll<int>(v1, );
eraseAll<int>(v1, );
eraseAll<int>(v1, ); /* 第二种逆向删除
eraseAll2<int>(v1, 9);
eraseAll2<int>(v1, 12);
eraseAll2<int>(v1, 15);
*/
cout << "(5) 删除9,12,15后 v1 容器元素如下:" << endl;
for_each(v1.begin(), v1.end(), printVectorValue<int>);
cout << endl;
/* 错误删除!!
for (itPt = v1.begin(); itPt != v1.end(); ++itPt)
{
if (14 == *itPt)
{
v1.erase(itPt);
}
}
*/ system("pause");
} // Run out
/*
(1) v1 容器元素如下:
9 9 9 9 9 9 10 11 12 13 14 15
(2) v1 容器元素如下:
9 9 9 9 9 10 11 12 13 14 15
(3) v1 容器元素如下:
9 9 9 10 11 12 13 14 15
(4) 删除前 v1 容器元素如下:
9 9 9 10 11 12 12 12 12 13 14 15 15 15
(5) 删除9,12,15后 v1 容器元素如下:
10 11 13 14
请按任意键继续. . .
*/

      规避开失效指针,完全可以正常删除。

    4.2 insert函数

    insert函数源码如下:

STL容器之vector

    insert函数两种情况分析如下:

STL容器之vector

    insert函数重载多,使用比较方便。

【4】vector总结

  相比C++内置的array数组类,vector模板类是有生命的、动态的、可塑性的数组,使用更方便,更健壮。

Good  Good  Study, Day  Day  Up.

顺序  选择  循环  总结