Vector容器
STL在C++中称为标准模板库。STL定义了一系列用途广泛的模板类和模板函数,它们可以用来实现许多通用的算法和数据结构。
标准模板库STL的核心内容是3个基本组件:容器、算法和迭代器。STL将这些组件结合在一起为许多程序设计难题提供实际可行的解决办法。
例:
list容器是一个线性表容器,它有一个成员函数是sort(),调用这个函数可以将list容器对象中的数据进行排序。
定义一个list对象list1,并加入数据
4 3 5 2 1
list1.sort()
1 2 3 4 5
动态数组vector容器
动态数值是指可以根据需要改变大小的数组。虽然在C++中数组的大小在编译时是固定的,因为程序在运行时不能改变数组的大小来适应程序需求。然而,vector可以根据需要来分配内存,从而解决这个问题。虽然vector是动态的,你仍然可以使用标准的数组下标运算来访问数组中的元素。
1.创建一个vector对象
#include<vector>
using namespace std;
vector<int> v1;
vector<char> v2;
2.向vector对象中添加数值
v1.push_back(0);
v1.push_back(1);
for (i=2; i<=10;i++) v1.push_back(i);
3.获得vector对象的大小
v1.size()
for (i=0; i<v1.size();i++)
cout << v1[i] << “ ” ;
4.获得vector对象中第一个和最后一个元素;
vector<int>::iterator p = v1.begin();
vector<int>::iterator p = v1.end();
5.在vector对象中插入元素;
vector<int>::iterator p = v1.begin();
p = p+2;
v1.insert(p, 2 , 100);
6.在vector对象中删除元素;
v1.erase(p, p+3);
7.修改vector对象中的内容;
v1[1] = v1[1] * v1[1]
v1[2] = v1[2] + 100
8.清除vector对象中的所有内容;
v1.clear()