C++STL泛型编程概要1.ppt
文本预览下载声明
MSTC课堂 (1) 创建list对象 四种方式: 创建空链表: list 类型T 对象名; 例如: list int table; //创建整型链表table 创建具有n个元素的链表: list 类型T 对象名(n); 例如: list int table(10); //创建整型链表table ,10个元素 创建具有n个元素的链表,指定元素初始值: list 类型T 对象名(n,初值); 例如: list int table(10,9); //创建整型链表table ,10个元素,每个元素值均为9 由已有list容器创建: list 类型T 对象名(已有对象名); 例如: list int t2(t1); //创建整型链表t1的副本t2 * 创建list链表 几种初始化list对象的方式 listT t1; list保存类型为T的对象。默认构造函数t1为空 listT t2(t1); t2是t1的一个副本 listT t3(n, i); t3包含n个值为i的元素 listT t4(n); t4包含有值初始化元素的n个结点 * #includeiostream #includelist using namespace std; int main() { listint t1(5); //创建链表 listint t3(3,9); listint::iterator it; t1.push_back(2); t1.push_front(3); listint t2(t1); //创建链表 for (it=t1.begin();it!=t1.end();it++) cout*it , ; coutendl; for (it=t2.begin();it!=t2.end();it++) cout*it , ; coutendl; for (it=t3.begin();it!=t3.end();it++) cout*it , ; coutendl; return 0; } 【例10】创建整型链表,输出全部元素值。 * (2) 元素插入 push_back在尾部插入元素; push_front在头部插入元素; insert向迭代器位置处插入新元素。 * 三个方法: 注意: 插入元素时,链表自动扩展; 不可自行修改迭代器。 insert(iterator it,T t): 对list容器在指定位置插入新元素 【例11】用insert向整型链表中插入元素,输出全部元素值。 #includeiostream #includelist using namespace std; int main() { listint t1(5); //创建链表 listint::iterator it; t1.push_back(2); t1.push_front(3); it=t1.begin(); it++;it++; t1.insert(it,100); for (it=t1.begin();it!=t1.end();it++) cout*it , ; coutendl; return 0; } 注意:链表的迭代器只能顺序逐位移动,不可+n * (3) 元素删除 remove删除链表中值相同的元素; pop_front删除链表首元素; pop_back删除链表尾元素; erase删除迭代器位置上的元素; clear方法删除所有元素. * 五个方法: remove删除链表中相同值元素 remove(T elem): 删除链表中所有与elem值相等的元素 【例12】list的remove方法示例。 #includeiostream #includelist using namespace std; int main() { listint t1; //创建链表 t1.push_back(20); t1.push_front(13); t1.push_back(100); t1.push_back(-19); t1.push_back(13); t1.push_back(-20); for (listint::iterator it=t1.begin();it!=t1.end();it++) cout*it , ; coutendl; t1.remove(13); //删除表中所有值为13的元素 for (listint::iterator it=t1.begin();it!
显示全部