顺序容器以线性方式存储序列元素,并且这些序列有头有尾,以此存放。序列的“头”为首元素,“尾”为末元素. 访问: 1、顺序访问:向量(vector),双端队列(deque),链表(list) 2、随机访问:向量(vector),双端队列(deque) 简单操作: tip:迭代器:用面向对象技术封装的高级指针(可理解为一种只能指针,后续文章会详细讲解)
/* C<T>::interator it 定义指定类型的迭代器对象 c.begin() 返回指向容器对象中首元素的迭代器 c.end() 返回指向容器对象中末元素后续位置的迭代器 //特别注意c.end()得到的并不是末元素的位置,如需得到末元素的位置,c.end()-1即可 c.rbegin 返回指向容器对象中逆向首元素的迭代器 c.rend() 返回指向容器对象中逆向末向首元素的迭代器 //特别注意c.rend()得到的并不是逆向末元素的位置,如需得到逆向末元素的位置,c.rend()-1即可 */ /* 逆向末 vector<char>::reverse_iterator it2; it2 = vc.rend()-1; cout << *it2 << endl; 逆向末向首元素 vector<char>::reverse_iterator it2; it2 = vc.rbegin(); cout << *it2 << endl; */ #include <iostream> #include <vector> #include <list> #include <iterator> using namespace std; void show(vector<char>v); int main() { char a[5] = {'a','b','c','d','e'}; vector <char>vc(a, a + 3);//利用a数组的数据,在区间[a,a+3)来构造vc向量对象,包含a位置的元素不包括a+3位置的元素 vector<char>::iterator itv;//定义向量迭代器 cout << "vc:初始值:"; show(vc); //插入 vc.insert(vc.begin(),'j');//插入;把j插入vc的首部 cout << "vc:首部插入j:"; show(vc); vc.push_back('w');//末端插入w cout << "vc:尾部插入w:"; show(vc); itv = vc.begin()+3; vc.insert(itv, '3'); cout << "vc:指定位置插入3:"; show(vc); //删除 vc.pop_back(); cout << "删除末端元素:"; show(vc); vc.erase(vc.begin() + 1, vc.end()-1); cout << "删除除第一个和最后一个元素之外的所有元素:"; show(vc); vc.erase(vc.begin() + 1); cout << "删除第二个元素:"; show(vc); cout << "容器的容量:" << vc.max_size() << endl; cout << "容器对象当前所包含元素的数量:" << vc.size() << endl; if (vc.empty()) cout << "容器为空" << endl; //if(vc.empty())等价于if(vc.size()==0) else cout << "容器不为空" << endl; system("pause"); return 0; } void show(vector<char>v) { vector<char>::iterator it;//定义向量迭代器 for (it = v.begin(); it != v.end(); it++) {//输出容器内的所有元素 cout << *it;//所有容器都要配合迭代器才能访问内部的元素,可以简单的把迭代器理解为智能指针 } cout << endl; }