//正向打印模板函数 templatevoid show_it(T& con) { typename T::iterator it = con.begin(); for (; it != con.end(); it++) { cout << *it << " "; } cout << endl; }
vectorv1; vector v2; for (int i = 0; i < 10; i++) { v1.push_back(i); } show_it(v1);
输出:0 1 2 3 4 5 6 7 8 9
1.2:reverse_iterator 反向迭代器//vector::iterator it = v1.begin();end()//正向迭代器 //vector ::reverse_iterator it = v1.rbegin();rend()//反向迭代器
//反向打印模板函数
templatevoid show_cr(T& src) { typename T::const_reverse_iterator it = src.crbegin(); for (; it != src.crend(); it++) { cout << *it << " "; } cout << endl; }
vector1.3:const_iterator 常量正向迭代器v1; vector v2; for (int i = 0; i < 10; i++) { v1.push_back(i); } show_it(v1); show_n(v1);
vector::const_iterator it2 = v2.cbegin();//常量迭代器vector ::const_reverse_iterator it1 = v2.crbegin();//反向常量迭代器
正向打印常量模板函数
template1.4:reverse_const_iterator 常量反向迭代器void show_const(const CON& src) { typename CON::const_iterator it = src.cbegin(); for (; it != src.cend(); it++) { cout << *it << " "; } cout << endl; }
//函数模板,常量反向打印容器内元素
//函数模板,常量反向打印容器内元素 template2.插入型迭代器void show_reverse_const(CON& src) { typename CON::const_reverse_iterator it = src.crbegin(); for (; it != src.crend(); it++) { cout << *it << " "; } cout << endl; }
2.1:insert_iterator 随机插入型迭代器 ----- insert
随机插入即能在任意位置插入。
vectorv1; vector v2; for (int i = 0; i < 10; i++) { v1.push_back(i); } show_it(v1); //show_n(v1); insert_iterator < vector >it(v2, v2.begin()); for (int i = 0; i < 10; i++) { *it = i + 100; } show_it(v2); insert_iterator >it1(v2, v2.begin()+1); Insert(v1.begin(), v1.end(), it1);//也可把it1直接定义为inserter(v2,v2.begin())
//函数模板封装类模板的产生
insert_iteratorminserter(T& con, typename T::iterator it)//返回类型是insert_iterator,传参时(对象,迭代器) { return insert_iterator (con, it); } Insert(v1.begin(), v1.end(), inserter(v2,v2.begin() + 1)); Insert(v1.begin(), v1.end(), minserter(v2, v2.begin() + 1));
2.2:back_insert_iterator 后插型迭代器 ------ push_back();
back_insert_iteratormback_inserter(T& con) { return back_insert_iterator (con); }
vectorv1; vector v2; for (int i = 0; i < 10; i++) { v1.push_back(i); } show_it(v1); insert_iterator < vector >it(v2, v2.begin()); for (int i = 0; i < 10; i++) { *it = i + 100; } show_it(v2); back_insert_iterator >it2(v2); *it2 = 999; show_it(v2); Insert(v1.begin(), v1.begin() + 4, back_inserter(v2));//和inserter相同 show_it(v2); Insert(v1.begin(), v1.begin() + 4,mback_inserter(v2)); show_it(v2);
2.3:front_insert_iterator 前插型迭代器 ----- push_front
前插存在于list.
list3.流迭代器:(输入和输出) 3.1:输出list1; for (int i = 0; i < 10; i++) { list1.push_back(i); } front_insert_iterator > it3(list1); auto it4 = front_inserter(list1); *it3 = 888; *it4 = 777; show(list1);
ostream_iterator3.2:输入ito(cout, " "); for (int i = 0; i < 10; i++) { ito = i; } cout << endl;
istream_iteratoriti(cin); int a; a = *iti; ostream_iterator ito(cout, " "); ito = a;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)