C++走向远洋——60(十四周阅读程序、STL中的简单容器和迭代器)
*/ * Copyright (c) 2016,烟台大学计算机与控制工程学院 * All rights reserved. * 文件名:text.cpp * 作者:常轩 * 微信公众号:Worldhello * 完成日期:2016年6月2日 * 版本号:V1.0 * 问题描述: 十四周阅读程序 * 程序输入:无 * 程序输出:见运行结果 */ #include<iostream> #include<vector> #include<iterator> using namespace std; int main() { vector<int> ivec; int i; for(i = 0; i < 5; i++ ) ivec.push_back(i); for(i = 0; i < 5; i++) cout<<ivec[i]<<" "; cout<<endl; while( !ivec.empty()) { cout << ivec.back() << " "; ivec.pop_back(); } cout << endl; for(i = 0; i < 5; i++) cout<<ivec[i]<<" "; cout<<endl; copy(ivec.begin(),ivec.end(),ostream_iterator<int>(cout, " ")); cout<<endl; cout << "size=" << ivec.size() << endl; return 0; }
运行结果:
//(2) #include <iostream> #include <vector> using namespace std; int main() { vector<int> intList; vector<int>::iterator listIt; int i; intList.push_back(1); intList.push_back(5); intList.push_back(10); intList.push_back(15); cout<<"Line 1: List Elements: "; for(i=0; i<4; i++) cout<<intList[i]<<" "; cout<<endl; for(i=0; i<4; i++) intList[i] *=2; cout<<"Line 2: List Elements: "; for(listIt=intList.begin(); listIt != intList.end(); ++listIt) cout<<*listIt<<" "; cout<<endl; listIt=intList.begin(); ++listIt; ++listIt; intList.insert(listIt,8); cout<<"Line 3: List Elements: "; for(listIt = intList.begin(); listIt != intList.end(); ++listIt) cout<<*listIt<<" "; cout<<endl; return 0; }
运行结果:
//(3) #include <iterator> #include <list> #include <algorithm> #include <iostream> using namespace std; int main() { int ia[5] = {1,2,3,4}; list<int> id(ia, ia+4); ostream_iterator<int> outite(cout, " "); copy(id.begin(), id.end(), outite); cout << endl; copy(ia+1, ia+2, front_inserter(id)); copy(id.begin(), id.end(), outite); cout << endl; copy(ia+3, ia+4, back_inserter(id)); copy(id.begin(), id.end(), outite); cout << endl; list<int>::iterator ite = find(id.begin(), id.end(), 3); copy(ia+0, ia+2, inserter(id, ite)); copy(id.begin(), id.end(), outite); cout << endl; copy(id.rbegin(), id.rend(), outite); cout << endl; return 0; }
运行结果: