STL之list
1 #include<iostream> 2 #include<algorithm> 3 #include<list> 4 using namespace std; 5 6 7 //初始化 8 void test01(){ 9 10 list<int> mlist1; 11 list<int> mlist2(10,10);//有参构造 12 list<int> mlist3(mlist2);//拷贝构造 13 list<int> mlist4(mlist2.begin(),mlist2.end()); 14 15 for(list<int>::iterator it=mlist4.begin(); it!=mlist4.end(); it++ ){ 16 cout<<(*it)<<" "; 17 } 18 cout<<endl; 19 } 20 21 //插入与删除 22 void test02(){ 23 list<int> mlist; 24 //插入操作 25 mlist.push_back(100); 26 mlist.push_front(200); 27 mlist.insert(mlist.begin(),300); 28 mlist.insert(mlist.end(),400); 29 mlist.insert(mlist.end(),200); 30 31 list<int>::iterator it =mlist.begin(); 32 it++; 33 it++; 34 mlist.insert(it,500); 35 mlist.insert(it,200); 36 37 //删除 38 /*mlist.pop_back(); 39 mlist.pop_front(); 40 41 mlist.erase(mlist.begin(),mlist.end());*///相当于mlist.clear() 42 mlist.remove(200);//删除匹配所有值 43 44 for(list<int>::iterator vec=mlist.begin(); vec!=mlist.end(); vec++ ){ 45 cout<<(*vec)<<" "; 46 } 47 cout<<endl; 48 49 } 50 51 //赋值操作 52 void test03(){ 53 list<int> mlist; 54 mlist.assign(10,10); 55 56 list<int> mlist2; 57 mlist2=mlist; 58 59 mlist.swap(mlist); 60 } 61 //排序反转 62 void test04(){ 63 list<int> mlist; 64 for( int i=0; i<10; i++ ){ 65 mlist.push_back(i); 66 } 67 for(list<int>::iterator it = mlist.begin(); it!=mlist.end(); it++ ){ 68 cout<<*it<<" "; 69 } 70 cout<<endl; 71 mlist.reverse(); 72 for(list<int>::iterator it = mlist.begin(); it!=mlist.end(); it++ ){ 73 cout<<*it<<" "; 74 } 75 } 76 77 //定义排序规则 78 bool mycompare(int& v1,int& v2){ 79 return v1>v2; 80 } 81 //排序 82 void test05(){ 83 list<int> mlist; 84 mlist.push_back(2); 85 mlist.push_back(1); 86 mlist.push_back(7); 87 mlist.push_back(5); 88 for(list<int>::iterator it = mlist.begin(); it!=mlist.end(); it++ ){ 89 cout<<*it<<" "; 90 } 91 cout<<endl; 92 mlist.sort();//默认从小到大排序 93 for(list<int>::iterator it = mlist.begin(); it!=mlist.end(); it++ ){ 94 cout<<*it<<" "; 95 } 96 cout<<endl; 97 mlist.sort(mycompare);//从大到小排序 98 for(list<int>::iterator it = mlist.begin(); it!=mlist.end(); it++ ){ 99 cout<<*it<<" "; 100 } 101 } 102 103 int main(){ 104 105 test05(); 106 return 0; 107 }
有些目标看似很遥远,但只要付出足够多的努力,这一切总有可能实现!