1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <iterator> 5 #include <fstream> 6 #include <deque> 7 #include <string> 8 #include <memory> 9 using namespace std; 10 11 //流迭代器 12 void main1() 13 { 14 //vector<int> v{ 1,2,3,4,5,6,7,8,9 }; 15 ////流迭代器,可以输出到屏幕,也可以输出到文件 16 //copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); 17 18 //写入到文件 19 //ofstream fout("1.txt"); 20 ////写入到文件再加入" " 21 //ostream_iterator<int> it_tofile(fout," "); 22 //copy(v.begin(), v.end(), it_tofile); 23 //fout.close(); 24 25 //system("1.txt"); 26 27 ifstream fin("1.txt"); 28 ofstream fout("2.txt"); 29 30 //读取迭代器 31 istream_iterator<string> it_fromfile(fin); 32 //写入迭代器 33 ostream_iterator<string> it_tofile(fout); 34 35 //从开始到结束复制到it_tofile中 36 copy(it_fromfile, istream_iterator<string>(), it_tofile); 37 38 fin.close(); 39 fout.close(); 40 41 system("2.txt"); 42 cin.get(); 43 } 44 45 //正反向迭代器 46 void main2() 47 { 48 vector<int> v{ 1,3,4,5,6,7,8,9 }; 49 //读写正向迭代 50 for (auto ib = v.begin(), ie = v.end(); ib != ie; ib++) 51 { 52 53 } 54 //只读正向迭代 55 for (auto ib = v.cbegin(), ie = v.cend(); ib != ie; ib++) 56 { 57 58 } 59 //读写反向迭代器 60 for (auto ib = v.rbegin(), ie = v.rend(); ib != ie; ib++) 61 { 62 63 } 64 //只读反向迭代器 65 for (auto ib = v.rbegin(), ie = v.rend(); ib != ie; ib++) 66 { 67 68 } 69 cin.get(); 70 } 71 72 //正向,反向,随机插入迭代器 73 void main3() 74 { 75 deque<int> myd{ 1,2,3,4,5 }; 76 77 //正向插入迭代器 位置在头部 78 front_insert_iterator<deque<int>> it(myd); 79 //反向插入迭代器 位置在尾部 80 back_insert_iterator<deque<int>> its(myd); 81 //随机插入迭代器 位置在随机位置 82 insert_iterator<deque<int>> itss(myd, myd.begin() + 3); 83 //反向迭代器 84 reverse_iterator <deque<int>::iterator> rb(myd.end()); 85 reverse_iterator <deque<int>::iterator> re(myd.begin()); 86 //通过反向迭代器反向输出 87 copy(rb, re, ostream_iterator<int>(cout, " ")); 88 89 *it = 1000; 90 91 for (auto i : myd) 92 { 93 cout << i << endl; 94 } 95 cin.get(); 96 } 97 98 class A 99 { 100 public: 101 int i; 102 103 public: 104 A(int num):i(num) 105 { 106 cout << " A()" << endl; 107 } 108 ~A() 109 { 110 cout << "~A()" << endl; 111 } 112 }; 113 114 void main() 115 { 116 //分配器(不会调用构造) 117 allocator<A> alloc; 118 A *p = alloc.allocate(10); 119 //存储迭代器 120 raw_storage_iterator<A*, A> rsi(p); 121 //保存临时对象,作用区域完了就销毁 122 for (int i = 0; i < 10; i++) 123 { 124 *rsi++ = A(i); 125 } 126 127 for (int i = 0; i < 10; i++) 128 { 129 cout << (int)((*p++).i) << endl; 130 } 131 132 //手动调用析构 133 for (int i = 0; i < 10; i++) 134 { 135 alloc.destroy(p+i); 136 } 137 138 //alloc.deallocate(p, 10); 139 cin.get(); 140 }