STL 迭代器(iterator)
直接代码加注释:
1.顺序迭代器:
直接代码加注释:
#include#include #include using namespace std; template void show(T&src)//函数模板 正向打印容器内元素 { typename T::iterator it = src.begin(); for (; it != src.end(); it++) { cout << *it << " "; } cout << endl; } template void show_reverse(T1& src)//函数模板,反向打印容器内元素 { typename T1::reverse_iterator it1 = src.rbegin(); for (; it1 != src.rend(); it1++) { cout << *it1 << " "; } cout << endl; } template void show_const(const T2& src)//函数模板,常量正向打印容器内元素 { typename T2::const_iterator it = src.cbegin(); for (; it != src.cend(); it++) { cout << *it << " "; } cout << endl; } template void show_const_reverse(const T3&src)//函数模板,常量反向打印容器内元素 { typename T3::const_reverse_iterator it = src.crbegin(); for (; it != src.crend(); it++) { cout << *it << " "; } cout << endl; } int main() { vector v1; for (int i = 0; i < 10; i++) { v1.push_back(i + 1); } show(v1); show_reverse(v1); cout << "-----------------------------------------------------------------------" << endl; const vector v2(v1.begin(), v1.end());//用v1初始化v2 show_const(v2); show_const_reverse(v2); return 0; }
2、插入迭代器
#include#include #include using namespace std; template void show(T&src)//函数模板 正向打印容器内元素 { typename T::iterator it = src.begin(); for (; it != src.end(); it++) { cout << *it << " "; } cout << endl; } template //定义插入型模板 void Insert(const IT& first, const IT& last, INSERT_IT insert_it) { IT tmp = first; for (; tmp != last; tmp++) { *insert_it = *tmp; } } int main() { vector v1; vector v2; for (int i = 0;i < 10; i++) { v1.push_back(i + 1);//初始化v1 } cout << "初始化v1" << endl; show(v1); insert_iterator > it(v2, v2.begin());//用v1初始化v2 for (int i = 0; i < 10; i++) { *it = i+1 + 100; } cout << "初始化v2" << endl; show(v2); insert_iterator > it1(v2, v2.begin() + 1);//随机插入型迭代器 Insert(v1.begin(), v1.end(), it1);//将v1开始到结束插入v2.begin()+1的位置 //Insert(v1.begin(), v1.end(), inserter(v2, v2.begin() + 1));//等价于上面 c++用inserter封装 cout << "随机型插型迭代器:" << endl; show(v2); back_insert_iterator > it2(v2);//尾插型迭代器 *it2 = 999;//将999插入v2后面 cout << "后插型迭代器:" << endl; show(v2); Insert(v1.begin(), v1.begin()+3, it2);//将v1.begin()到v1.begin()+3的值插入v2后面 //Insert(v1.begin(), v1.begin() + 3, back_inserter(v2)); cout << "后插型迭代器 插入区间值:" << endl; show(v2); return 0; }
vector容器类底层实现一维数组 没有头插
用list容器示范:
listlist1; for (int i = 0; i < 10; i++) { list1.push_back(i + 1); } cout << "初始化list" << endl; show(list1); front_insert_iterator > it(list1); auto it1 = front_inserter(list1);//auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型,类似的关键字还有decltype。 *it = 888; *it1 = 777; cout << "前插型迭代器" << endl; show(list1);
3、流迭代器
ostream_iteratorito(cout, " "); for (int i = 0; i < 10; i++) { ito = i; } cout << endl; Insert(list1.begin(), list1.end(), ito);//用输出流打印list(已存在) cout << endl; istream_iterator iti(cin);//输入数字用输出流打印 int a; a = *iti; ito = a;
后面代码断层 为了方便 重复的没有写 可在上面找相应函数实现
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)