C++ STL基础
模板
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 template<class T> 3 class MyArray 4 { 5 private: 6 int m_nTotalSize; 7 int m_nValidSize; 8 T * m_pData; 9 public: 10 MyArray(int nSize = 3) 11 { 12 m_pData = new T[nSize]; 13 m_nTotalSize = nSize; 14 m_nValidSize = 0; 15 } 16 17 void Add(T value) 18 { 19 if(m_nValidSize < m_nTotalSize) 20 { 21 m_pData[m_nValidSize] = value; 22 m_nValidSize ++; 23 } 24 25 else 26 { 27 T * tmpData = new T[m_nTotalSize]; 28 for(int i = 0 ; i < m_nTotalSize ;i ++) 29 tmpData[i] = m_pData[i]; 30 delete [] m_pData; 31 32 m_nTotalSize *= 2; 33 m_pData = new T[m_nTotalSize]; 34 for(int i = 0 ;i < m_nValidSize ;i ++) 35 m_pData[i] = tmpData[i]; 36 delete [] tmpData; 37 m_pData[m_nValidSize] = value; 38 m_nValidSize ++; 39 } 40 } 41 42 int GetSize() 43 { 44 return m_nValidSize; 45 } 46 47 T Get(int pos) 48 { 49 return m_pData[pos]; 50 } 51 52 virtual ~MyArray() 53 { 54 if(m_pData != NULL) 55 { 56 delete [] m_pData; 57 m_pData = NULL; 58 } 59 } 60 }; 61 62 63 64 int main(int argc,char *argv[]) 65 { 66 MyArray<int> obj; 67 obj.Add(1); 68 obj.Add(2); 69 obj.Add(3); 70 obj.Add(4); 71 72 for(int i = 0 ;i < obj.GetSize() ;i ++) 73 printf("%d\n",obj.Get(i)); 74 75 return 0 ; 76 }
STL标准模板库非常强调 软件复用,traits技术是采用的重要手段。traits中文意思是特性。traits依靠显式模板特殊化来把代码中因类型不同而发生变化的片段拖出来,用统一的接口来包装
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 class CIntArray 5 { 6 int a[10]; 7 public: 8 9 CIntArray() 10 { 11 for(int i = 0 ;i < 10 ;i ++) 12 a[i] = i + 1 ; 13 } 14 15 int GetSum(int times) 16 { 17 int sum = 0; 18 for(int i = 0; i < 10 ;i ++) 19 sum += a[i]; 20 return sum*times; 21 } 22 }; 23 24 25 class CFloatArray 26 { 27 float f[10]; 28 public: 29 CFloatArray() 30 { 31 for(int i = 1 ;i < 10 ;i ++) 32 f[i-1] = 1.0f/i; 33 } 34 35 float GetSum(float times) 36 { 37 float sum = 0.0f; 38 39 for(int i = 0; i < 10 ;i ++) 40 sum += f[i]; 41 42 return sum * times; 43 } 44 }; 45 46 int main() 47 { 48 CIntArray intary; 49 CFloatArray fltary; 50 cout << "Int array sum 3 times is :" << intary.GetSum(3) << endl; 51 cout << "Float array sum 3.2 times is :" << fltary.GetSum(3.2f) << endl; 52 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 class CIntArray 5 { 6 int a[10]; 7 public: 8 9 CIntArray() 10 { 11 for(int i = 0 ;i < 10 ;i ++) 12 a[i] = i + 1 ; 13 } 14 15 int GetSum(int times) 16 { 17 int sum = 0; 18 for(int i = 0; i < 10 ;i ++) 19 sum += a[i]; 20 return sum*times; 21 } 22 }; 23 24 25 class CFloatArray 26 { 27 float f[10]; 28 public: 29 CFloatArray() 30 { 31 for(int i = 1 ;i < 10 ;i ++) 32 f[i-1] = 1.0f/i; 33 } 34 35 float GetSum(float times) 36 { 37 float sum = 0.0f; 38 39 for(int i = 0; i < 10 ;i ++) 40 sum += f[i]; 41 42 return sum * times; 43 } 44 }; 45 46 template<class T> 47 class CApply 48 { 49 public: 50 float GetSum(T &t,float inpara) 51 { 52 return t.GetSum(inpara); 53 } 54 }; 55 56 57 int main() 58 { 59 CIntArray intary; 60 CFloatArray fltary; 61 CApply<CIntArray> c1; 62 CApply<CFloatArray> c2; 63 cout << "Int array sum 3 times is :" << c1.GetSum(intary,3) << endl; 64 cout << "Float array sum 3.2 times is :" << c2.GetSum(fltary,3.2f) << endl; 65 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 class CIntArray 5 { 6 int a[10]; 7 public: 8 9 CIntArray() 10 { 11 for(int i = 0 ;i < 10 ;i ++) 12 a[i] = i + 1 ; 13 } 14 15 int GetSum(int times) 16 { 17 int sum = 0; 18 for(int i = 0; i < 10 ;i ++) 19 sum += a[i]; 20 return sum*times; 21 } 22 }; 23 24 25 class CFloatArray 26 { 27 float f[5]; 28 public: 29 CFloatArray() 30 { 31 for(int i = 1 ;i <= 5 ;i ++) 32 f[i-1] = 1.0f * i; 33 } 34 35 float GetSum(float times) 36 { 37 float sum = 0.0f; 38 39 for(int i = 0; i < 5 ;i ++) 40 sum += f[i]; 41 42 return sum * times; 43 } 44 }; 45 46 template<class T> 47 class NumTraits 48 { 49 50 }; 51 52 template<> class NumTraits<CIntArray> 53 { 54 public: 55 typedef int resulttype; 56 typedef int inputpara; 57 }; 58 59 template<> class NumTraits<CFloatArray> 60 { 61 public: 62 typedef float resulttype; 63 typedef float inputpara; 64 }; 65 /* 66 template<class T> 67 class CApply 68 { 69 public: 70 // typedef NumTraits<T>::resulttype result; 71 // typedef NumTraits<T>::inputpara inputpara; 72 73 NumTraits<T>::resulttype GetSum(T &obj,NumTraits<T>::inputpara in) 74 { 75 return obj.GetSum(in); 76 } 77 }; 78 */ 79 80 template<class T> 81 class CApply 82 { 83 public: 84 typedef typename NumTraits<T>::resulttype result; 85 typedef typename NumTraits<T>::inputpara inputpara; 86 result GetSum(T &t,inputpara inpara) 87 { 88 return t.GetSum(inpara); 89 } 90 }; 91 92 int main() 93 { 94 CIntArray intary; 95 CFloatArray fltary; 96 CApply<CIntArray> c1; 97 CApply<CFloatArray> c2; 98 cout << "Int array sum 3 times is :" << c1.GetSum(intary,3) << endl; 99 cout << "Float array sum 3 times is :" << c2.GetSum(fltary,3.0f) << endl; 100 }
迭代器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 template<class T> 5 class MyArray 6 { 7 private: 8 int m_nTotalSize; 9 int m_nValidSize; 10 T * m_pData; 11 public: 12 MyArray(int nSize = 3) 13 { 14 m_pData = new T[nSize]; 15 m_nTotalSize = nSize; 16 m_nValidSize = 0; 17 } 18 19 void Add(T value) 20 { 21 if(m_nValidSize < m_nTotalSize) 22 { 23 m_pData[m_nValidSize] = value; 24 m_nValidSize ++; 25 } 26 27 else 28 { 29 T * tmpData = new T[m_nTotalSize]; 30 for(int i = 0 ; i < m_nTotalSize ;i ++) 31 tmpData[i] = m_pData[i]; 32 delete [] m_pData; 33 34 m_nTotalSize *= 2; 35 m_pData = new T[m_nTotalSize]; 36 for(int i = 0 ;i < m_nValidSize ;i ++) 37 m_pData[i] = tmpData[i]; 38 delete [] tmpData; 39 m_pData[m_nValidSize] = value; 40 m_nValidSize ++; 41 } 42 } 43 44 int GetSize() 45 { 46 return m_nValidSize; 47 } 48 49 T Get(int pos) 50 { 51 return m_pData[pos]; 52 } 53 54 T * Begin() 55 { 56 return m_pData; 57 } 58 59 T * End() 60 { 61 return m_pData + m_nValidSize; 62 } 63 64 65 virtual ~MyArray() 66 { 67 if(m_pData != NULL) 68 { 69 delete [] m_pData; 70 m_pData = NULL; 71 } 72 } 73 }; 74 75 template<class T> 76 struct Unit 77 { 78 T value; 79 Unit * next; 80 }; 81 82 template<class T> 83 class MyLink 84 { 85 Unit<T> * head; 86 Unit<T> * tail; 87 Unit<T> * prev; 88 89 public: 90 MyLink() 91 { 92 head = tail = prev = NULL; 93 } 94 95 void Add(T &value) 96 { 97 Unit<T> * u = new Unit<T>(); 98 u -> value = value; 99 u -> next = NULL; 100 if(head == NULL) 101 { 102 head = u; 103 prev = u; 104 } 105 else 106 { 107 prev -> next = u; 108 prev = u; 109 } 110 tail = u -> next; 111 } 112 113 Unit<T> * Begin() 114 { 115 return head; 116 } 117 118 Unit<T> * End() 119 { 120 return tail; 121 } 122 123 virtual ~ MyLink() 124 { 125 if(head != NULL) 126 { 127 Unit<T> * prev = head; 128 Unit<T> * next = NULL; 129 while( prev != tail) 130 { 131 next = prev -> next; 132 delete prev; 133 prev = next; 134 } 135 } 136 } 137 }; 138 139 140 template<class Init> 141 class ArrayIterator 142 { 143 Init * init; 144 public: 145 ArrayIterator(Init * init) 146 { 147 this -> init = init; 148 } 149 150 bool operator != (ArrayIterator & it) 151 { 152 return this->init <= it.init; 153 } 154 155 void operator ++ (int) 156 { 157 init ++; 158 } 159 160 Init operator*() 161 { 162 return *init; 163 } 164 }; 165 166 template<class Init> 167 class LinkIterator 168 { 169 Init * init; 170 public: 171 LinkIterator(Init *init) 172 { 173 this -> init = init; 174 } 175 176 bool operator != (LinkIterator & it) 177 { 178 return this->init != it.init; 179 } 180 181 void operator ++ (int) 182 { 183 init = init->next; 184 } 185 186 Init operator * () 187 { 188 return *init; 189 } 190 }; 191 192 193 template<class T> 194 ostream & operator << (ostream &os ,Unit<T> &s) 195 { 196 os << s.value; 197 return os; 198 } 199 200 201 202 template<class Init> 203 void display(Init start,Init end) 204 { 205 cout << endl; 206 for(Init mid = start ; mid != end ; mid ++) 207 cout << *mid << '\t'; 208 cout << endl; 209 } 210 211 /* 212 int main() 213 { 214 MyArray<int> ary; 215 for(int i = 0; i < 5 ;i ++) 216 { 217 ary.Add(i + 1); 218 } 219 ArrayIterator<int> start(ary.Begin()); 220 ArrayIterator<int> end(ary.End()); 221 cout << "Array element is: "; 222 display(start,end); 223 224 return 0; 225 } 226 */ 227 int main() 228 { 229 int m = 0; 230 MyLink<int> ml; 231 for(int i = 0;i < 5 ;i ++) 232 { 233 m = i + 1; 234 ml.Add(m); 235 } 236 237 LinkIterator<Unit<int> > start(ml.Begin()); 238 LinkIterator<Unit<int> > end(ml.End()); 239 240 display(start,end); 241 242 return 0; 243 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 5 template<class T> 6 class MyLink 7 { 8 public: 9 struct Unit 10 { 11 T value; 12 Unit * next; 13 }; 14 15 class LinkIterator 16 { 17 Unit *init; 18 public: 19 LinkIterator(Unit *init) 20 { 21 this -> init = init; 22 } 23 24 bool operator != (LinkIterator &it) 25 { 26 return this->init != it.init; 27 } 28 29 void operator ++ (int) 30 { 31 init = init -> next; 32 } 33 34 Unit operator * () 35 { 36 return *init; 37 } 38 }; 39 40 Unit * head; 41 Unit * tail; 42 Unit * prev; 43 44 public: 45 MyLink() 46 { 47 head = tail = prev = NULL; 48 } 49 50 void Add(T &value) 51 { 52 Unit * u = new Unit(); 53 u -> value = value; 54 u -> next = NULL; 55 if(head == NULL) 56 { 57 head = u; 58 prev = u; 59 } 60 else 61 { 62 prev -> next = u; 63 prev = u; 64 } 65 tail = u -> next; 66 } 67 68 Unit * Begin() 69 { 70 return head; 71 } 72 73 Unit * End() 74 { 75 return tail; 76 } 77 78 virtual ~ MyLink() 79 { 80 if(head != NULL) 81 { 82 Unit* prev = head; 83 Unit* next = NULL; 84 while( prev != tail) 85 { 86 next = prev -> next; 87 delete prev; 88 prev = next; 89 } 90 } 91 } 92 }; 93 94 95 template<class T> 96 ostream & operator << (ostream &os, typename MyLink<T>::Unit & s) 97 { 98 os << s.value; 99 return os; 100 } 101 102 template<class Init> 103 void display(Init start,Init end) 104 { 105 cout << endl; 106 for(Init mid = start ; mid != end ; mid ++) 107 cout << *mid << '\t' ; 108 109 cout << endl; 110 } 111 112 int main() 113 { 114 int m = 0; 115 MyLink<int> ml; 116 117 for(int i = 0; i < 5 ;i ++) 118 { 119 m = i + 1; 120 ml.Add(m); 121 } 122 123 MyLink<int>::LinkIterator start = ml.Begin(); 124 MyLink<int>::LinkIterator end = ml.End; 125 display(start,end); 126 127 return 0; 128 }
STL迭代器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <iterator> 3 using namespace std; 4 5 int main(int argc,char * argv[]) 6 { 7 cout << "Please input data: "; 8 istream_iterator<int> a(cin); 9 10 istream_iterator<int> b; 11 12 while(1) 13 { 14 cout << *a << endl; 15 a ++; 16 if( a == b) 17 break; 18 } 19 20 return 0; 21 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <iterator> 3 using namespace std; 4 5 int main(int argc,char * argv[]) 6 { 7 cout << "ostream_iterator result: "; 8 ostream_iterator<int> myout(cout,"\t"); 9 10 *myout = 1; 11 myout ++; 12 *myout = 2; 13 myout ++; 14 *myout = 3; 15 16 return 0; 17 }
输入输出流
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int i; 7 float f; 8 char str[20]; 9 10 cin >> i ; 11 cin >> f; 12 cin >> str; 13 14 cout << "i = " << i << endl; 15 cout << "f = " << f << endl; 16 cout << "str = " << str << endl; 17 18 return 0; 19 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int i ; 7 char str[20]; 8 9 cout << "Please input a integer and a string: "; 10 cin >> i >> str; 11 12 cout << "i = " << i << endl; 13 cout << "str = " << str << endl; 14 15 return 0; 16 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 char szBuf[60]; 7 cout << "Please input a string: "; 8 int n = cin.get(); 9 cin.getline(szBuf,60); 10 cout << n << endl; 11 cout << "The received string is :" << szBuf << endl; 12 13 return 0; 14 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int a; 7 cout << "Please input a data: "; 8 cin >> a ; 9 cout << "state is : " << cin.rdstate() << endl; 10 11 if(cin.good()) 12 cout << "the type inputed is right,no error!" << endl; 13 if(cin.fail()) 14 cout << "the type inputed is wrong,is error!" << endl; 15 if(cin.bad()) 16 cout << "deadly wrong!!!" << endl; 17 else 18 cout << "can go on!" << endl; 19 20 return 0; 21 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int a; 7 8 while(1) 9 { 10 cin >> a; 11 if(cin.fail()) 12 { 13 cout << "Input error ! again ..." << endl; 14 cin.clear(); 15 cin.get(); 16 } 17 else 18 { 19 cout << a << endl; 20 break; 21 } 22 } 23 24 return 0; 25 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <fstream> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 char szBuf[80]; 8 ifstream in("iostream.cpp"); 9 if(!in) 10 return 0; 11 while(in.getline(szBuf,80)) 12 { 13 cout << szBuf << endl; 14 } 15 16 in.close(); 17 18 return 0; 19 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <fstream> 2 #include <iostream> 3 4 using namespace std; 5 6 struct STUDENT 7 { 8 char strName[20]; 9 int nGrade; 10 }; 11 12 int main() 13 { 14 ofstream out; 15 out.open("a.txt"); 16 STUDENT st1={"zhangsan",90}; 17 STUDENT st2={"lisi",80}; 18 19 out << st1.strName << "\t" << st1.nGrade << endl; 20 out << st2.strName << "\t" << st1.nGrade << endl; 21 22 out.close(); 23 24 return 0; 25 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <fstream> 2 #include <iostream> 3 4 using namespace std; 5 6 struct STUDENT 7 { 8 char strName[20]; 9 int nGrade; 10 }; 11 12 int main() 13 { 14 ofstream out; 15 out.open("b.txt"); 16 STUDENT st1={"zhangsan",90}; 17 STUDENT st2={"lisi",80}; 18 19 out.write((const char *)&st1,sizeof(STUDENT)); 20 out.write((const char *)&st2,sizeof(STUDENT)); 21 22 out.close(); 23 24 return 0; 25 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <fstream> 2 #include <iostream> 3 using namespace std; 4 5 struct STUDENT 6 { 7 char strName[20]; 8 int nGrade; 9 }; 10 11 int main() 12 { 13 ifstream in; 14 in.open("b.txt"); 15 if(!in) 16 return 0; 17 18 STUDENT st1; 19 STUDENT st2; 20 21 in.read((char*)&st1,sizeof(STUDENT)); 22 in.read((char*)&st2,sizeof(STUDENT)); 23 24 cout << st1.strName << "\t" << st1.nGrade << endl; 25 cout << st2.strName << "\t" << st2.nGrade << endl; 26 27 in.close(); 28 29 return 0 ; 30 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <fstream> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 ifstream fin("b.txt"); 8 if(fin != NULL) 9 { 10 cout << fin.rdbuf(); 11 } 12 13 fin.close(); 14 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <fstream> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 fstream in_out; 8 in_out.open("sb.txt",ios::in | ios::out | ios::trunc); 9 in_out.write("Hello",5); 10 11 in_out.seekg(0,ios::beg); 12 cout << in_out.rdbuf(); 13 in_out.close(); 14 15 return 0; 16 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <sstream> 3 4 using namespace std; 5 6 int main() 7 { 8 int n; 9 float f; 10 string strHello; 11 12 string strText = "1 3.14 hello"; 13 istringstream s(strText); 14 s >> n; 15 s >> f; 16 s >> strHello; 17 18 cout << "n= " << n << endl; 19 cout << "f= " << f << endl; 20 cout << "strHello= " << strHello << endl; 21 22 return 0; 23 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <sstream> 3 using namespace std; 4 5 int main() 6 { 7 cout << "type an int,a float and a string: "; 8 int i; 9 float f; 10 string stuff; 11 cin >> i >> f; 12 getline(cin,stuff); 13 ostringstream os; 14 os << "integer=" << i << endl; 15 os << "float = " << f << endl; 16 os << "string = " << stuff << endl; 17 18 string result = os.str(); 19 cout << result << endl; 20 21 return 0; 22 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class Student 6 { 7 public: 8 string strName; 9 string strSex; 10 int nAge; 11 }; 12 13 istream & operator >> (istream &is,Student &s) 14 { 15 is >> s.strName >> s.strSex >> s.nAge; 16 return is; 17 } 18 19 ostream & operator << (ostream &os,Student &s) 20 { 21 os << s.strName << "\t" << s.strSex << "\t" << s.nAge << endl; 22 return os; 23 } 24 25 ostream & operator << (ostream &os,const Student &s) 26 { 27 cout << "const Student output is: " << endl; 28 os << s.strName << "\t" << s.strSex << "\t" << s.nAge << endl; 29 return os; 30 } 31 32 void f(const Student &s) 33 { 34 35 cout << s; 36 } 37 38 int main(int argc, char *argv[]) 39 { 40 Student s; 41 cout << "Please input data(name,sex,age): "; 42 cin >> s; 43 cout << "Input data is: "; 44 cout << s; 45 46 return 0; 47 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <fstream> 3 #include <sstream> 4 #include <string> 5 6 7 using namespace std; 8 9 10 int main(int argc,char *argv[]) 11 { 12 ifstream in("sb.txt"); 13 14 string strText; 15 string strName; 16 int nYuwen; 17 int nMath; 18 int nForeign; 19 int nTotal; 20 21 while(!in.eof()) 22 { 23 getline(in,strText); 24 istringstream inf(strText); 25 26 inf >> strName >> nYuwen >> nMath >> nForeign; 27 28 nTotal = nYuwen + nMath + nForeign; 29 30 cout << strName <<"\t\t\t" << nYuwen << "\t\t\t" << nMath << "\t\t\t" << nForeign << "\t\t\t" << nTotal << endl; 31 } 32 33 in.close(); 34 35 return 0; 36 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <fstream> 3 #include <sstream> 4 #include <string> 5 6 using namespace std; 7 8 class Student 9 { 10 public: 11 string strName; 12 int nYuwen; 13 int nMath; 14 int nForeign; 15 }; 16 17 18 istream &operator >> (istream & is,Student &s) 19 { 20 is >> s.strName >> s.nYuwen >> s.nMath >> s.nForeign; 21 return is; 22 } 23 24 ostream &operator << (ostream &os, Student &s) 25 { 26 int nTotal = s.nYuwen + s.nMath + s.nForeign; 27 os << s.strName << "\t" << s.nYuwen << "\t" << s.nMath << "\t" << s.nForeign << "\t" << nTotal << endl; 28 return os; 29 } 30 31 int main() 32 { 33 ifstream in("sb.txt"); 34 Student s; 35 36 while(!in.eof()) 37 { 38 in >> s; 39 cout << s; 40 } 41 42 in.close(); 43 44 return 0; 45 }
字符串
字符串类减少了C语言编程中三种常见且最具破坏性的错误:
1,超越数组边界
2,通过未被初始化或被赋以错误值的指针来访问数组元素
3,在释放了某一数组原先所分配的存储单元后仍保留了“悬挂”指针
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 using namespace std; 3 4 int main() 5 { 6 string s1; 7 string s2("How are you?"); 8 string s3(s2); 9 string s4(s2,0,3); 10 string s5("Fine"); 11 string s6=s2+"Fine"; 12 13 return 0; 14 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 int main() 6 { 7 string s1 = "How are you?"; 8 string s2(s1.begin(),s1.end()); 9 string s3(s1.begin()+4,s1.begin()+7); 10 11 cout << s1 << endl << s2 << endl << s3 << endl; 12 return 0; 13 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 string s = "do"; 8 cout << "Inition size is: " << s.size() << endl; 9 s.insert(0,"How "); 10 s.append(" you"); 11 s = s + " do?"; 12 13 cout << "final size is: " << s.size() << endl; 14 15 cout << s; 16 17 return 0 ; 18 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 #include <iostream> 3 4 using namespace std; 5 6 int main() 7 { 8 string s = "what's your name?"; 9 cout << "Before replace : " << s << endl; 10 s.replace(7,4,"her"); 11 cout << "After repalce : " << s << endl; 12 13 return 0 ; 14 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 string s = " what's your name? my name is TOM. How do you do ? Fine,thanks. "; 8 int n = s.find("your"); 9 cout << "the first your pos: " << n << endl; 10 n = s.find("you",15); 11 cout << "the first your pos begin from 15:" << n << endl; 12 n = s.find_first_of("abcde"); 13 cout << "find pos when character within abcde: " << n << endl; 14 n = s.find_last_of("abcde",3); 15 cout << "find last pos begin from 2 when character within abcde: " << n << endl; 16 17 n = s.find_first_not_of("abcde"); 18 cout << "find pos when character without abcde: " << n << endl; 19 n = s.find_last_not_of("abcde"); 20 cout << "find last pos when character without abcde: " << n << endl; 21 22 23 return 0; 24 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 string s1 = "How are you?"; 8 s1.erase(s1.begin(),s1.begin()+3); 9 cout << "after erase to s1 is : " << s1 << endl; 10 11 string s2 = "Fine, thanks"; 12 s2.erase(s2.begin(),s2.end()); 13 cout << "after erase to s2 is: " << s2 << endl; 14 15 return 0; 16 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 string s1 = "this"; 8 string s2 = "that"; 9 10 if(s1 > s2) 11 cout << "s1>s2" << endl; 12 if(s1 == s2) 13 cout << "s1 = s2" << endl; 14 if(s1 < s2) 15 cout << "s1 < s2" << endl; 16 17 return 0; 18 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 #include <iostream> 3 #include <sstream> 4 using namespace std; 5 6 7 int main() 8 { 9 int n1 = 10 ; 10 string s1; 11 stringstream os1; 12 os1 << n1; 13 os1 >> s1; 14 15 cout << "make integer 10 to string 10: " << s1 << endl; 16 17 int n2 = 0; 18 string s2 = "123"; 19 stringstream os2; 20 os2 << s2; 21 os2 >> n2; 22 cout << "make string 123 to integer 123: " << n2 << endl; 23 24 return 0 ; 25 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 int main() 6 { 7 string strText = "How are you?"; 8 string strSeparator = " "; 9 string strResult; 10 int size_pos = 0; 11 int size_prev_pos = 0 ; 12 13 while((size_pos = strText.find_first_of(strSeparator,size_pos)) != string::npos) 14 { 15 strResult = strText.substr(size_prev_pos,size_pos - size_prev_pos); 16 17 cout << "string = " << strResult << endl; 18 size_prev_pos = ++ size_pos; 19 } 20 21 if(size_prev_pos != strText.size()) 22 { 23 strResult = strText.substr(size_prev_pos,size_pos - size_prev_pos); 24 cout << "string = " << strResult << endl; 25 } 26 27 return 0; 28 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <sstream> 3 #include <string> 4 using namespace std; 5 6 int main() 7 { 8 string strResult = " "; 9 string strText = "How are you"; 10 istringstream istr(strText); 11 12 while(!istr.eof()) 13 { 14 istr >> strResult; 15 cout << "string = " << strResult << endl; 16 } 17 18 return 0 ; 19 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <sstream> 3 #include <string> 4 using namespace std; 5 6 int main() 7 { 8 string strResult = " "; 9 string strText = "How,are,you"; 10 11 istringstream istr(strText); 12 13 while(! istr.eof()) 14 { 15 getline(istr,strResult,','); 16 cout << "string = " << strResult << endl; 17 } 18 19 return 0; 20 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 string s = " hello "; 8 s.erase(0,s.find_first_not_of(" ")); 9 s.erase(s.find_last_not_of(" ")+1); 10 11 cout << s ; 12 13 return 0; 14 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <string> 2 #include <sstream> 3 #include <iostream> 4 using namespace std; 5 6 class ext_string : public string 7 { 8 public: 9 int GetInt(string strText) 10 { 11 int n = 0; 12 stringstream os; 13 os << strText; 14 os >> n; 15 return n; 16 } 17 18 string GetString(int n) 19 { 20 string s; 21 stringstream os; 22 os << n; 23 os >> s; 24 25 return s; 26 } 27 28 string GetTrim(string strText) 29 { 30 strText.erase(0,strText.find_first_not_of(" ")); 31 strText.erase(strText.find_last_not_of(" ") + 1); 32 return strText; 33 } 34 }; 35 36 int main() 37 { 38 ext_string extstring; 39 int n = extstring.GetInt("123"); 40 string s1 = extstring.GetString(456); 41 string s2 = extstring.GetTrim(" hello "); 42 43 cout << "The string '123' convert to integer is: " << n << endl; 44 cout << "The integer 456 convert to string is : " << s1 << endl; 45 cout << "The string erase space is : " << s2 << endl; 46 47 return 0 ; 48 }
函数对象
函数对象是重载了 oprator()的类的一个实例,operator()是函数调用运算符。标准C++库根据operator()参数个数为0个,1个,2个加以划分,主要有下3中类型:
发生器: 一种没有参数且返回一个任意类型值的函数对象,例如随机数发生器
一元函数: 一种只有一个任意类型的参数,且返回一个可能不同类型值的函数对象
二元函数: 一种有两个任意类型的参数,且返回一个任意类型值的函数对象
一元判定函数: 返回bool型值的一元函数
二元判定函数: 返回bool型值的二元函数
可见,函数对象最多仅适用于两个参数
STL中一元函数基类是一个模板类:
template<class _A,class _R>
struct unary_function
{
typedef _A argument_type;
typedef _B result_type;
};
例子:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <algorithm> 2 #include <iostream> 3 #include<vector> 4 5 using namespace std; 6 7 8 class CSum 9 { 10 private: 11 int sum; 12 public: 13 CSum() { sum = 0;} 14 15 void operator()(int n) 16 { 17 sum += n; 18 } 19 20 int GetSum() { return sum;} 21 }; 22 23 24 int main() 25 { 26 vector<int> v; 27 for(int i = 1;i <= 100 ;i ++) 28 { 29 v.push_back(i); 30 } 31 32 CSum sObj = for_each(v.begin(),v.end(),CSum()); 33 34 cout << "sum = " << sObj.GetSum() << endl; 35 36 return 0; 37 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <algorithm> 3 #include <functional> 4 #include <vector> 5 using namespace std; 6 7 template<class _inPara,class _outPara> 8 class CSum : public unary_function<_inPara, _outPara> 9 { 10 public: 11 _outPara sum; 12 CSum() { sum = 0; } 13 void operator() (_inPara n) 14 { 15 sum += n; 16 } 17 18 _outPara GetSum() { return sum; } 19 }; 20 21 int main() 22 { 23 vector<int> v; 24 25 for(int i = 1; i <= 100; i ++) 26 v.push_back(i); 27 28 CSum<int,int> sObj = for_each(v.begin(),v.end(),CSum<int,int>()); 29 cout << "sum(int) = " << sObj.GetSum() << endl; 30 31 vector<float> v2; 32 float f = 1.3f; 33 for(int i = 1 ;i<= 99 ;i ++) 34 { 35 v2.push_back(f); 36 f += 1.0f; 37 } 38 39 CSum<float,float> sObj2 = for_each(v2.begin(),v2.end(),CSum<float,float>() ); 40 cout << "sum(float) = " << sObj2.GetSum() << endl; 41 42 return 0; 43 }
STL中二元函数基类是一个模板类:
template<class Arg1,class Arg2,class Result>
struct binary_function
{
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
X
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <algorithm> 3 #include <iostream> 4 #include <vector> 5 #include <string> 6 #include <iterator> 7 using namespace std; 8 9 10 class Student 11 { 12 public: 13 string name; 14 int grade; 15 public: 16 Student(string name,int grade) 17 { 18 this -> name = name; 19 this -> grade = grade; 20 } 21 22 bool operator < (const Student & s) const 23 { 24 return grade < s.grade; 25 } 26 }; 27 28 29 ostream & operator << (ostream &os,const Student &s) 30 { 31 os << s.name << '\t' << s.grade << endl; 32 return os; 33 } 34 35 36 template<class _inPara1,class _inPara2> 37 class binary_sort : public binary_function<_inPara1,_inPara2,bool> 38 { 39 public: 40 bool operator () (_inPara1 in1,_inPara2 in2) 41 { 42 return in1 < in2; 43 } 44 }; 45 46 47 int main() 48 { 49 Student s1("zhangsan",60); 50 Student s2("lisi",80); 51 Student s3("wangwu",70); 52 Student s4("zhaoliu",90); 53 54 vector<Student> v; 55 56 v.push_back(s1); 57 v.push_back(s2); 58 v.push_back(s3); 59 v.push_back(s4); 60 61 sort(v.begin(),v.end(),binary_sort<Student &,Student &>()); 62 copy(v.begin(),v.end(),ostream_iterator<Student>(cout,"")); 63 64 return 0; 65 }
STL内置函数对象:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <iostream> 3 using namespace std; 4 5 6 int main() 7 { 8 plus<int> plusObj; 9 minus<int> minusObj; 10 multiplies<int> mulObj; 11 divides<int> divObj; 12 modulus<int> modObj; 13 negate<int> negObj; 14 15 cout << plusObj(2,4) << endl; 16 cout << minusObj(2,4) << endl; 17 cout << mulObj(2,4) << endl; 18 cout << divObj(2,4) << endl; 19 cout << modObj(5,3) << endl; 20 cout << negObj(4) << endl; 21 22 cout << plus<int>()(2,4) << endl; 23 cout << minus<int>()(2,4) << endl; 24 cout << multiplies<int>()(2,4) << endl; 25 cout << divides<int>()(2,4) << endl; 26 cout << modulus<int>()(5,3) << endl; 27 cout << negate<int>()(4) << endl; 28 29 return 0; 30 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <iostream> 3 using namespace std; 4 5 class Complex 6 { 7 public: 8 float real; 9 float virt; 10 public: 11 Complex() 12 { 13 this->real = 0.0f; 14 this->virt = 0.0f; 15 } 16 17 Complex(float real,float virt) 18 { 19 this -> real = real; 20 this -> virt = virt; 21 } 22 23 Complex operator + (const Complex &c) const 24 { 25 Complex v; 26 v.real = real + c.real; 27 v.virt = virt + c.virt; 28 29 return v; 30 } 31 }; 32 33 34 int main() 35 { 36 Complex c1(1.0f,2.0f); 37 Complex c2(3.0f,4.0f); 38 Complex c3 = c1 + c2; 39 40 Complex c4 = plus<Complex>()(c1,c2); 41 42 cout << c3.real << "+" << c3.virt << "i" << endl; 43 cout << c4.real << "+" << c4.virt << "i" << endl; 44 45 return 0; 46 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <numeric> 2 #include <iostream> 3 #include <functional> 4 #include <vector> 5 using namespace std; 6 7 class Complex 8 { 9 public: 10 float real; 11 float virt; 12 public: 13 Complex() 14 { 15 this->real = 0.0f; 16 this->virt = 0.0f; 17 } 18 19 Complex(float real,float virt) 20 { 21 this -> real = real; 22 this -> virt = virt; 23 } 24 25 Complex operator + (const Complex &c) const 26 { 27 Complex v; 28 v.real = real + c.real; 29 v.virt = virt + c.virt; 30 31 return v; 32 } 33 }; 34 35 36 int main() 37 { 38 Complex c1(1.0f,2.0f); 39 Complex c2(3.0f,4.0f); 40 Complex c3 = c1 + c2; 41 42 Complex c4 = plus<Complex>()(c1,c2); 43 44 Complex c; 45 46 vector<Complex> v; 47 v.push_back(c1); 48 v.push_back(c2); 49 v.push_back(c3); 50 v.push_back(c4); 51 52 Complex result = accumulate(v.begin(),v.end(),c,plus<Complex>()); 53 54 cout << result.real << "+" << result.virt << "i" << endl; 55 56 return 0; 57 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <iostream> 3 4 using namespace std; 5 6 int main() 7 { 8 equal_to<int> equalObj; 9 not_equal_to<int> notequalObj; 10 greater<int> greatObj; 11 greater_equal<int> greatequalObj; 12 less<int> lessObj; 13 less_equal<int> lessequalObj; 14 15 16 cout << equalObj(2,4) << endl; 17 cout << notequalObj(2,4) << endl; 18 cout << greatObj(2,4) << endl; 19 cout << greatequalObj(2,4) << endl; 20 cout << lessObj(2,4) << endl; 21 cout << lessequalObj(2,4) << endl; 22 23 cout << equal_to<int>()(2,4) << endl; 24 cout << not_equal_to<int>()(2,4) << endl; 25 cout << greater<int>()(2,4) << endl; 26 cout << greater_equal<int>()(2,4) << endl; 27 cout << less<int>()(2,4) << endl; 28 cout << less_equal<int>()(2,4) << endl; 29 30 return 0; 31 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 logical_and<int> andObj; 8 logical_or<int> orObj; 9 logical_not<int> notObj; 10 11 cout << andObj(true,true) << endl; 12 cout << orObj(true,false) << endl; 13 cout << notObj(true) << endl; 14 15 cout << logical_and<int>()(3<5,6<9); 16 cout << logical_or<int>()(3<5,6<9); 17 cout << logical_not<int>()(3<5); 18 19 return 0; 20 }
函数适配器:
1,可以形成复杂的,有语义的表达式
2,可以调用类中普通的成员函数
例子:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iterator> 2 #include <functional> 3 #include <algorithm> 4 #include <iostream> 5 using namespace std; 6 7 int main() 8 { 9 int a[] = {1,3,5,7,9,8,6,4,2,0}; 10 11 int nCount = count_if(a,a+sizeof(a)/sizeof(int),bind2nd(less<int>(),4)); 12 cout << nCount << endl; 13 14 nCount = count_if(a,a+sizeof(a)/sizeof(int),bind1st(less<int>(),4)); 15 cout << nCount << endl; 16 17 nCount = count_if(a,a+sizeof(a)/sizeof(int),not1(bind2nd(less<int>(),4))); 18 cout << nCount << endl; 19 20 nCount = count_if(a,a+sizeof(a)/sizeof(int),not1(bind1st(less<int>(),4))); 21 cout << nCount << endl; 22 23 sort(a,a+sizeof(a)/sizeof(int),not2(less<int>())); 24 copy(a,a+sizeof(a)/sizeof(int),ostream_iterator<int>(cout," ")); 25 26 return 0; 27 }
X
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <algorithm> 3 #include <iostream> 4 #include <vector> 5 #include <string> 6 7 using namespace std; 8 9 class Student 10 { 11 string strNO; 12 string strName; 13 public: 14 Student(string strNO,string strName) : strNO(strNO),strName(strName){} 15 bool show() 16 { 17 cout << strNO << ":" << strName << endl; 18 return true; 19 } 20 }; 21 22 int main() 23 { 24 Student s1("1001","zhangsan"); 25 Student s2("1002","lisi"); 26 27 vector<Student> v; 28 v.push_back(s1); 29 v.push_back(s2); 30 for_each(v.begin(),v.end(),mem_fun_ref(Student::show)); 31 32 Student *ps1 = new Student("1003","wangwu"); 33 Student *ps2 = new Student("1004","zhaoliu"); 34 vector<Student *> pv; 35 pv.push_back(ps1); 36 pv.push_back(ps2); 37 38 for_each(pv.begin(),pv.end(),mem_fun(Student::show)); 39 40 return 0; 41 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <algorithm> 3 #include <iostream> 4 using namespace std; 5 6 bool f(int x) 7 { 8 return x > 3; 9 } 10 11 bool g(int x,int y) 12 { 13 return x > y; 14 } 15 16 17 int main() 18 { 19 int a[] = {2,5,3,7,1,9,8,0,6}; 20 21 int nSize = sizeof(a) / sizeof(int); 22 int nCount = count_if(a,a+nSize,f); 23 cout << nCount << endl; 24 25 nCount = count_if(a,a+nSize,ptr_fun(f)); 26 cout << nCount << endl; 27 28 nCount = count_if(a,a+nSize,bind2nd(ptr_fun(g),3)); 29 cout << nCount << endl; 30 31 nCount = count_if(a,a+nSize,bind2nd(ptr_fun(g),5)); 32 cout << nCount << endl; 33 34 return 0; 35 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <algorithm> 3 #include <iostream> 4 #include <vector> 5 using namespace std; 6 7 class Shape 8 { 9 public: virtual bool ShowArea() = 0; 10 }; 11 12 class Circle : public Shape 13 { 14 float r; 15 public: 16 Circle(float r) : r(r){} 17 bool ShowArea() { 18 cout << 3.14 * r * r << endl; 19 return true; 20 } 21 }; 22 23 class Rectangle : public Shape 24 { 25 float width,height; 26 public: 27 Rectangle(float width,float height) : width(width),height(height) {} 28 bool ShowArea() { 29 cout << width * height << endl; 30 return true; 31 } 32 }; 33 34 class AreaCollect 35 { 36 vector<Shape *> v; 37 public: 38 bool Add(Shape * pShape) 39 { 40 v.push_back(pShape); 41 return true; 42 } 43 44 bool ShowEachArea() 45 { 46 for_each(v.begin(),v.end(),mem_fun(Shape::ShowArea)); 47 return true; 48 } 49 }; 50 51 int main() 52 { 53 AreaCollect contain; 54 Shape * pObj1 = new Circle(10.0f); 55 Shape * pObj2 = new Rectangle(10.0f,20.0f); 56 57 contain.Add(pObj1); 58 contain.Add(pObj2); 59 contain.ShowEachArea(); 60 61 return 0; 62 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <functional> 2 #include <algorithm> 3 #include <iostream> 4 #include <vector> 5 #include <iterator> 6 #include <string> 7 8 using namespace std; 9 10 class Student 11 { 12 public: 13 string strNO; 14 int nGrade; 15 public: 16 Student(string strNO,int nGrade) : strNO(strNO),nGrade(nGrade) {} 17 }; 18 19 class StudIndex : public binary_function<int,int,bool> 20 { 21 vector<Student> &vStud; 22 public: 23 StudIndex(vector<Student>&vStud) : vStud(vStud) {} 24 25 bool operator() (int a,int b) 26 { 27 return vStud.at(a).nGrade < vStud.at(b).nGrade; 28 } 29 }; 30 31 int main() 32 { 33 Student s1("1001",70); 34 Student s2("1002",60); 35 Student s3("1003",80); 36 Student s4("1004",74); 37 38 vector<Student> v; 39 v.push_back(s1); 40 v.push_back(s2); 41 v.push_back(s3); 42 v.push_back(s4); 43 44 vector<int> vIndex; 45 vIndex.push_back(0); 46 vIndex.push_back(1); 47 vIndex.push_back(2); 48 vIndex.push_back(3); 49 50 sort(vIndex.begin(),vIndex.end(),StudIndex(v)); 51 copy(vIndex.begin(),vIndex.end(),ostream_iterator<int>(cout," ")); 52 53 return 0; 54 }
通用容器
vector容器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <vector> 2 #include <iostream> 3 4 using namespace std; 5 6 int main() 7 { 8 vector<int> int_vec; 9 10 int_vec.push_back(1); 11 int_vec.push_back(2); 12 int_vec.push_back(3); 13 14 int nSize = int_vec.size(); 15 16 cout << "Array output style : "; 17 for(int i = 0; i < nSize ;i ++) 18 { 19 cout << int_vec[i] << "\t"; 20 } 21 cout << endl; 22 23 cout << "output via reference: "; 24 for(i = 0 ;i < nSize ;i++) 25 { 26 int &nValue = int_vec.at(i); 27 cout << nValue << "\t"; 28 } 29 cout << endl; 30 31 cout << "output via iterator: "; 32 vector<int>::iterator int_vec_iter = int_vec.begin(); 33 while(int_vec_iter != int_vec.end()) 34 { 35 cout << *int_vec_iter << "\t" ; 36 int_vec_iter ++; 37 } 38 39 cout << endl; 40 41 return 0; 42 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <vector> 2 #include <iostream> 3 using namespace std; 4 5 class A 6 { 7 public: 8 int n; 9 public: 10 A(int n) 11 { 12 this -> n = n; 13 } 14 }; 15 16 int main() 17 { 18 cout << "Part one: class A vector operator" << endl; 19 20 vector<A> ca_vec; 21 A a1(1); 22 A a2(2); 23 ca_vec.push_back(a1); 24 ca_vec.push_back(a2); 25 int nSize = ca_vec.size(); 26 27 cout << "\noutput via array:"; 28 for(int i = 0 ; i < nSize; i++) 29 { 30 cout << ca_vec[i].n << "\t"; 31 } 32 cout << "\noutput via reference: "; 33 for(i = 0 ;i < nSize ;i ++) 34 { 35 A & a = ca_vec.at(i); 36 cout << a.n << "\t"; 37 } 38 cout << "\noutput via iterator: "; 39 vector<A>::iterator ca_vec_iter = ca_vec.begin(); 40 while(ca_vec_iter != ca_vec.end()) 41 { 42 cout << (*ca_vec_iter).n << "\t"; 43 ca_vec_iter ++; 44 } 45 46 cout << "\nPart two: class A pointer vector" << endl; 47 48 vector<A *> pca_vec; 49 50 A * pa1 = new A(1); 51 A * pa2 = new A(2); 52 53 pca_vec.push_back(pa1); 54 pca_vec.push_back(pa2); 55 56 nSize = pca_vec.size(); 57 58 cout <<"output via array: "; 59 for(i = 0 ; i < nSize ;i ++) 60 { 61 cout << pca_vec[i] -> n << "\t"; 62 } 63 64 cout << "\noutput via reference : "; 65 for(i = 0 ; i < nSize ;i ++) 66 { 67 A * & a = pca_vec.at(i); 68 cout << a->n << "\t"; 69 } 70 71 cout << "\noutput via iterator: "; 72 vector<A *>::iterator pca_vec_iter = pca_vec.begin(); 73 while(pca_vec_iter != pca_vec.end()) 74 { 75 cout << (**pca_vec_iter).n << "\t"; 76 pca_vec_iter ++; 77 } 78 79 delete pa1; 80 delete pa2; 81 82 return 0; 83 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //modify.cpp 2 #include <vector> 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 vector<int> int_vec; 9 int_vec.push_back(1); 10 int_vec.push_back(2); 11 int_vec.push_back(3); 12 13 cout << "Modify via array: Element two will be modified to 5:"; 14 int_vec[1] = 5; 15 16 for(int i = 0 ; i < int_vec.size() ;i ++) 17 cout << int_vec[i] << "\t"; 18 cout << endl; 19 20 21 cout << "modify via reference: Element two will be modified to 10:"; 22 int &m = int_vec.at(1); 23 m = 10; 24 for(i = 0 ;i < int_vec.size() ; i++) 25 cout << int_vec[i] << "\t"; 26 cout << endl; 27 28 cout << "modify via iterator: Element two will be modified to 20: "; 29 vector<int>::iterator int_vec_iter = int_vec.begin() + 1; 30 *int_vec_iter = 20; 31 32 for(i = 0 ;i < int_vec.size() ;i++) 33 cout << int_vec[i] << "\t"; 34 cout << endl; 35 36 return 0; 37 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //erase.cpp 2 #include <vector> 3 #include <iostream> 4 using namespace std; 5 6 7 int main() 8 { 9 vector<int> int_vec; 10 for(int i = 1 ;i <= 10 ;i++) 11 int_vec.push_back(i); 12 13 int_vec.erase(int_vec.begin()+4); 14 cout << "erase the fivth element:"; 15 for(i = 0 ;i < int_vec.size() ;i ++) 16 cout << int_vec[i] << "\t"; 17 cout << endl; 18 19 int_vec.erase(int_vec.begin()+1,int_vec.begin()+5); 20 cout << "erase Element 2 ~ 5: "; 21 for(i = 0 ;i < int_vec.size() ;i ++) 22 cout << int_vec[i] << "\t"; 23 cout << endl; 24 25 return 0; 26 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //final1.cpp 2 #include <iostream> 3 #include <vector> 4 #include <string> 5 6 using namespace std; 7 8 class Student 9 { 10 public: 11 string m_strNO; 12 string m_strName; 13 string m_strSex; 14 string m_strDate; 15 public: 16 Student(string strNO,string strName,string strSex,string strDate) : 17 m_strNO(strNO),m_strName(strName),m_strSex(strSex),m_strDate(strDate) {} 18 19 void Display() { 20 cout << m_strNO << "\t" << m_strName << "\t" << m_strSex << "\t" << m_strDate << endl; 21 } 22 }; 23 24 class StudCollect 25 { 26 vector<Student> m_vStud; 27 public: 28 void Add(Student &s) { 29 m_vStud.push_back(s); 30 } 31 32 Student *Find(string strNO) { 33 bool bFind = false; 34 35 for(int i = 0 ;i < m_vStud.size(); i ++) 36 { 37 Student &s = m_vStud.at(i); 38 if(s.m_strNO == strNO) 39 { 40 bFind = true; 41 break; 42 } 43 } 44 45 Student *s = NULL; 46 if(bFind) 47 s = &m_vStud.at(i); 48 49 return s; 50 } 51 }; 52 53 int main() { 54 Student s1("1001","zhangsan","boy","1985-10-10"); 55 Student s2("1002","lisi","boy","1984-06-10"); 56 Student s3("1003","wangwu","boy","1985-11-15"); 57 StudCollect s; 58 s.Add(s1),s.Add(s2),s.Add(s3); 59 60 Student *ps = s.Find("1002"); 61 62 if(ps) 63 ps->Display(); 64 65 return 0; 66 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //final2.cpp 2 #include <iostream> 3 #include <vector> 4 #include <string> 5 using namespace std; 6 7 class Book 8 { 9 string m_strBookNO; 10 string m_strBookName; 11 string m_strPublic; 12 public: 13 Book(string strNO,string strName,string strPublic): 14 m_strBookNO(strNO),m_strBookName(strName),m_strPublic(strPublic) 15 { 16 ; 17 } 18 }; 19 20 class Writer 21 { 22 string m_strWriteNO; 23 string m_strWriteName; 24 vector<Book>m_vecBook; 25 public: 26 Writer(string strNO,string strName):m_strWriteNO(strNO),m_strWriteName(strName) {} 27 void AddBook(Book &book) { 28 m_vecBook.push_back(book); 29 } 30 }; 31 32 class WriterCollect 33 { 34 vector<Writer> m_vecWriter; 35 public: 36 void AddWriter(Writer & writer) { 37 m_vecWriter.push_back(writer); 38 } 39 }; 40 41 int main() { 42 Writer w1("1001","zhangsan"); 43 Book b1("b001","aaa","public"); 44 Book b2("b002","bbb","public"); 45 w1.AddBook(b1); 46 w1.AddBook(b2); 47 48 Writer w2("1002","lisi"); 49 Book b3("b003","ccc","public"); 50 w2.AddBook(b3); 51 52 WriterCollect collect; 53 collect.AddWriter(w1); 54 collect.AddWriter(w2); 55 56 return 0; 57 }
deque容器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //final2.cpp 2 #include <iostream> 3 #include <vector> 4 #include <string> 5 using namespace std; 6 7 class Book 8 { 9 string m_strBookNO; 10 string m_strBookName; 11 string m_strPublic; 12 public: 13 Book(string strNO,string strName,string strPublic): 14 m_strBookNO(strNO),m_strBookName(strName),m_strPublic(strPublic) 15 { 16 ; 17 } 18 }; 19 20 class Writer 21 { 22 string m_strWriteNO; 23 string m_strWriteName; 24 vector<Book>m_vecBook; 25 public: 26 Writer(string strNO,string strName):m_strWriteNO(strNO),m_strWriteName(strName) {} 27 void AddBook(Book &book) { 28 m_vecBook.push_back(book); 29 } 30 }; 31 32 class WriterCollect 33 { 34 vector<Writer> m_vecWriter; 35 public: 36 void AddWriter(Writer & writer) { 37 m_vecWriter.push_back(writer); 38 } 39 }; 40 41 int main() { 42 Writer w1("1001","zhangsan"); 43 Book b1("b001","aaa","public"); 44 Book b2("b002","bbb","public"); 45 w1.AddBook(b1); 46 w1.AddBook(b2); 47 48 Writer w2("1002","lisi"); 49 Book b3("b003","ccc","public"); 50 w2.AddBook(b3); 51 52 WriterCollect collect; 53 collect.AddWriter(w1); 54 collect.AddWriter(w2); 55 56 return 0; 57 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <vector> 3 #include <deque> 4 using namespace std; 5 6 int main() 7 { 8 vector<int> v(2); 9 v[0] = 10; 10 int *p = &v[0]; 11 cout << "In the Vector the first iterator element *p is: " << *p << endl; 12 v.push_back(20); 13 cout << "After varity the vector first iterator element *p is : " << *p << endl; 14 15 deque<int> d(2); 16 d[0] = 10; 17 int *q = &d[0]; 18 cout << "deque first iterator element *q is : " << *q << endl; 19 d.push_back(20); 20 cout << "After varity the deque first iterator element *q is : " << *q << endl; 21 22 return 0; 23 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //final.cpp 2 #include <iostream> 3 #include <deque> 4 using namespace std; 5 6 template<class T> 7 class MyQueue 8 { 9 deque<T> d; 10 public: 11 void push(const T&t) 12 { 13 d.push_back(t); 14 } 15 16 void pop() 17 { 18 d.pop_front(); 19 } 20 21 int size() 22 { 23 return d.size(); 24 } 25 26 bool empty() 27 { 28 return d.empty(); 29 } 30 31 T &front() 32 { 33 return *d.begin(); 34 } 35 36 T &back() 37 { 38 return *(--d.end()); 39 } 40 41 void display() 42 { 43 for(int i = 0 ;i < d.size() ;i ++) 44 cout << d.at(i) << "\t"; 45 } 46 }; 47 48 int main() 49 { 50 MyQueue<int> myqueue; 51 for(int i = 1 ; i <= 5 ;i ++) 52 { 53 myqueue.push(i); 54 } 55 56 cout << "original queue: "; 57 myqueue.display(); 58 cout << endl; 59 myqueue.pop(); 60 cout << "After delete the front:"; 61 myqueue.display(); 62 cout << endl; 63 myqueue.push(6); 64 cout << "After insert element 6: "; 65 myqueue.display(); 66 cout << endl; 67 68 cout << "Current the front element: " << myqueue.front() << endl; 69 cout << "Current the tail elemet : " << myqueue.back() << endl; 70 71 return 0; 72 }
list容器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 #include <list> 4 using namespace std; 5 6 typedef list<string> LISTSTR; 7 8 int main() 9 { 10 LISTSTR test; 11 12 test.push_back("back"); 13 test.push_front("middle"); 14 test.push_front("front"); 15 16 cout << test.front() << endl; 17 cout << * test.begin() << endl; 18 19 cout << test.back() << endl; 20 cout << *(test.rbegin()) << endl; 21 22 test.pop_front(); 23 test.pop_back(); 24 25 cout << test.front() << endl; 26 27 return 0; 28 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <list> 3 using namespace std; 4 5 typedef list<int> LISTINT; 6 7 int main() 8 { 9 LISTINT test; 10 11 for(int i = 0 ;i < 5 ;i ++) 12 test.push_back(i + 1); 13 14 LISTINT::iterator it = test.begin(); 15 16 for(; it != test.end() ;it ++) 17 cout << *it << "\t"; 18 cout << endl; 19 20 21 LISTINT::reverse_iterator rit = test.rbegin(); 22 23 for(; rit != test.rend() ; rit ++) 24 { 25 cout << *rit << "\t"; 26 } 27 cout << endl; 28 29 return 0; 30 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <list> 3 using namespace std; 4 5 typedef list<int> LISTINT; 6 7 int main() 8 { 9 LISTINT t1; 10 11 t1.push_back(1); 12 t1.push_back(5); 13 t1.push_back(3); 14 t1.push_back(10); 15 16 LISTINT t2; 17 t2.push_back(2); 18 t2.push_back(8); 19 t2.push_back(6); 20 t2.push_back(9); 21 22 t1.sort(); 23 t2.sort(); 24 25 t1.merge(t2); 26 27 for(LISTINT::iterator it = t1.begin() ; it != t1.end() ;it ++) 28 cout << *it << "\t"; 29 30 cout << endl; 31 32 cout << t1.size() << "\t" << t2.size() << endl; 33 34 return 0 ; 35 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <list> 3 #include <string> 4 using namespace std; 5 6 class Student 7 { 8 private: 9 string m_strNO; 10 string m_strName; 11 string m_strUniversity; 12 int m_nTotal; 13 public: 14 Student(string strNO,string strName,string strUniversity,int nTotal) : m_strNO(strNO), 15 m_strName(strName),m_strUniversity(strUniversity),m_nTotal(nTotal) 16 { 17 ; 18 } 19 20 bool operator < (Student &s) 21 { 22 return m_strNO < s.GetNO(); 23 } 24 25 bool operator == (Student &s) 26 { 27 return m_strNO == s.GetNO(); 28 } 29 30 string GetNO() { return m_strNO; } 31 string GetName() { return m_strName; } 32 string GetUniversity() { return m_strUniversity; } 33 34 int GetTotal() { return m_nTotal; } 35 }; 36 37 ostream & operator << (ostream &os,Student &s) 38 { 39 os << s.GetNO() << "\t" << s.GetName() << "\t" << s.GetUniversity() << "\t" << s.GetTotal(); 40 return os; 41 } 42 typedef list<Student> LISTSTUD; 43 44 class StudManage 45 { 46 private: 47 LISTSTUD m_stlList; 48 public: 49 bool Add(const Student &s) 50 { 51 m_stlList.push_back(s); 52 return true; 53 } 54 55 bool Merge(StudManage & stud) 56 { 57 m_stlList.sort(); 58 stud.m_stlList.sort(); 59 m_stlList.merge(stud.m_stlList); 60 m_stlList.unique(); 61 62 return true; 63 } 64 65 void Show() 66 { 67 for(LISTSTUD::iterator it = m_stlList.begin() ; it != m_stlList.end() ; it ++) 68 cout << *it << endl; 69 } 70 }; 71 72 73 int main() 74 { 75 StudManage sm1; 76 StudManage sm2; 77 78 Student s1("1001","zhangsan","tsinghua",670); 79 Student s2("1002","lisi","beida",660); 80 Student s3("1003","wangwu","fudan",650); 81 Student s4("1004","zhaoliu","nankai",640); 82 Student s5("1005","zhouqi","tongji",630); 83 84 85 sm1.Add(s1); 86 sm1.Add(s2); 87 sm1.Add(s5); 88 89 sm2.Add(s5); 90 sm2.Add(s4); 91 sm2.Add(s3); 92 sm2.Add(s1); 93 94 95 sm1.Merge(sm2); 96 97 sm1.Show(); 98 99 return 0; 100 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <list> 3 #include <string> 4 5 using namespace std; 6 7 class Term 8 { 9 private: 10 int coef; 11 int exp; 12 public: 13 Term(int coef,int exp) : coef(coef),exp(exp) 14 { 15 ; 16 } 17 18 int GetCoef() { return coef; } 19 int GetExp() { return exp; } 20 bool operator < (Term &t) 21 { 22 return exp < t.GetExp(); 23 } 24 }; 25 26 typedef list<Term>LISTTERM; 27 28 ostream & operator<<(ostream &os,Term &t) 29 { 30 os << t.GetCoef() << "x" << t.GetExp(); 31 return os; 32 } 33 34 class Polynomial 35 { 36 private: 37 LISTTERM m_stlTermList; 38 public: 39 bool AddTerm(const Term & t) 40 { 41 m_stlTermList.push_back(t); 42 return true; 43 } 44 45 Polynomial AddPolynomial(Polynomial & obj) 46 { 47 Polynomial result; 48 49 m_stlTermList.sort(); 50 obj.m_stlTermList.sort(); 51 52 LISTTERM::iterator src = m_stlTermList.begin(); 53 LISTTERM::iterator des = obj.m_stlTermList.begin(); 54 55 int coef = 0 ; 56 int exp = 0; 57 58 while((src != m_stlTermList.end()) && (des != obj.m_stlTermList.end())) 59 { 60 int nCurExp1 = (*src).GetExp(); 61 int nCurExp2 = (*des).GetExp(); 62 63 if(nCurExp1 == nCurExp2) 64 { 65 coef = (*src).GetCoef() + (*des).GetCoef(); 66 exp = (*src).GetExp(); 67 src ++; 68 des ++; 69 } 70 71 if(nCurExp1 < nCurExp2) 72 { 73 coef = (*src).GetCoef(); 74 exp = (*src).GetExp(); 75 76 src ++; 77 } 78 79 if(nCurExp1 > nCurExp2) 80 { 81 coef = (*des).GetCoef(); 82 exp = (*des).GetExp(); 83 84 des ++; 85 } 86 87 if(coef != 0) 88 { 89 Term t(coef,exp); 90 91 result.AddTerm(t); 92 } 93 } 94 95 if(src != m_stlTermList.end()) 96 { 97 LISTTERM temp(src,m_stlTermList.end()); 98 result.m_stlTermList.splice(result.m_stlTermList.end(),temp); 99 } 100 101 if(des != m_stlTermList.end()) 102 { 103 LISTTERM temp(des,obj.m_stlTermList.end()); 104 result.m_stlTermList.splice(result.m_stlTermList.end(),temp); 105 } 106 107 return result; 108 } 109 110 void Show() 111 { 112 LISTTERM::iterator it = m_stlTermList.begin(); 113 while(it != m_stlTermList.end()) 114 { 115 cout << *it << " + "; 116 117 it ++; 118 } 119 } 120 }; 121 122 int main() 123 { 124 Polynomial p1; 125 Polynomial p2; 126 127 Term t1(2,6); 128 Term t2(3,4); 129 Term t3(5,2); 130 Term t4(6,0); 131 132 p1.AddTerm(t1); 133 p1.AddTerm(t2); 134 p1.AddTerm(t3); 135 p1.AddTerm(t4); 136 137 Term t5(2,5); 138 Term t6(-3,4); 139 Term t7(5,2); 140 Term t8(8,0); 141 142 p2.AddTerm(t5); 143 p2.AddTerm(t6); 144 p2.AddTerm(t7); 145 p2.AddTerm(t8); 146 147 Polynomial p3 = p1.AddPolynomial(p2); 148 149 p3.Show(); 150 151 return 0; 152 }
queue && stack
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #pragma warning(disable:4786) 2 #include <iostream> 3 #include <string> 4 #include <vector> 5 #include <list> 6 #include <stack> 7 8 using namespace std; 9 10 void PrintStack(stack<int,vector<int> >obj) 11 { 12 while(!obj.empty()) 13 { 14 cout << obj.top() << "\t"; 15 obj.pop(); 16 } 17 } 18 19 void PrintStack(stack<string,list<string> >obj) 20 { 21 while(!obj.empty()) 22 { 23 cout << obj.top() << "\t"; 24 obj.pop(); 25 } 26 } 27 28 template<class T,class Container> 29 void PrintStack(stack<T,Container> obj) 30 { 31 while(!obj.empty()) 32 { 33 cout << obj.top() << "\t"; 34 obj.pop(); 35 } 36 } 37 38 int main() 39 { 40 stack<int,vector<int> > s; 41 for(int i = 0 ;i < 4 ;i ++) 42 s.push(i+1); 43 44 PrintStack(s); 45 cout << endl; 46 47 string str = "a"; 48 stack<string,list<string> > t; 49 for(i = 0 ; i < 4 ;i ++) 50 { 51 t.push(str); 52 str += "a"; 53 } 54 PrintStack(t); 55 cout << endl; 56 57 stack<float,deque<float> > u; 58 for(i = 0 ;i < 4 ;i ++) 59 u.push(i+1); 60 PrintStack(u); 61 62 return 0; 63 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #pragma warning(disable:4786) 2 #include <iostream> 3 #include <string> 4 #include <list> 5 #include <deque> 6 #include <queue> 7 using namespace std; 8 9 template<class T,class Container> 10 void PrintQueue(queue<T,Container> obj) 11 { 12 while(!obj.empty()) 13 { 14 cout << obj.front() << "\t"; 15 obj.pop(); 16 } 17 } 18 19 20 int main() 21 { 22 string str = "a"; 23 queue<string,deque<string> >t; 24 25 for(int i = 0 ; i < 4; i ++) 26 { 27 t.push(str); 28 str += "a"; 29 } 30 PrintQueue(t); 31 cout << endl; 32 33 queue<float,list<float> > u; 34 for(i = 0 ;i < 4 ;i ++) 35 { 36 u.push(i + 1); 37 } 38 39 PrintQueue(u); 40 41 return 0; 42 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <deque> 3 #include <stack> 4 using namespace std; 5 6 7 template<class T,class Container=deque<T> > 8 class mystack : public stack<T,Container> 9 { 10 private: 11 int m_nMaxSize ; 12 public: 13 mystack(int maxsize) 14 { 15 m_nMaxSize = maxsize; 16 } 17 18 void push(const T &t) 19 { 20 if(this->size() < m_nMaxSize) 21 { 22 stack<T,Container>::push(t); 23 } 24 else 25 { 26 cout << "stack is fill." << "the term " << t << " is not pushed" << endl; 27 } 28 } 29 }; 30 31 32 int main() 33 { 34 mystack<int,deque<int> >obj(2); 35 36 obj.push(1); 37 obj.push(2); 38 obj.push(3); 39 40 return 0 ; 41 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 #include <stack> 4 5 using namespace std; 6 7 class CExpress 8 { 9 private: 10 string m_strExpress; 11 public: 12 CExpress(string strExpress) : m_strExpress(strExpress) 13 {} 14 15 bool IsValid() 16 { 17 bool flag = true; 18 char ch = 0 ; 19 char chstack = 0; 20 stack<char>sta_char; 21 int size = m_strExpress.length(); 22 23 for(int i = 0 ;i < size ;i ++) 24 { 25 ch = m_strExpress.at(i); 26 if(ch == '(' || ch == '[') 27 sta_char.push(ch); 28 if(ch == ')' || ch == ']') 29 if(sta_char.empty()) 30 { 31 flag = false; 32 break; 33 } 34 else 35 { 36 chstack = sta_char.top(); 37 if(chstack == '(' && ch == ')' ) 38 sta_char.pop(); 39 else if(chstack == '[' && ch == ']') 40 sta_char.pop(); 41 else 42 { 43 flag = false; 44 break; 45 } 46 } 47 } 48 49 if(flag == true && !sta_char.empty()) 50 flag = false; 51 52 return flag; 53 } 54 }; 55 56 int main() 57 { 58 CExpress c1(")[]"); 59 CExpress c2("([]"); 60 CExpress c3("()["); 61 CExpress c4(")([]"); 62 CExpress c5("([]())"); 63 64 c1.IsValid() == true ? cout << "c1 is right" << endl : cout << "c1 is wrong" << endl; 65 c2.IsValid() == true ? cout << "c2 is right" << endl : cout << "c2 is wrong" << endl; 66 c3.IsValid() == true ? cout << "c3 is right" << endl : cout << "c3 is wrong" << endl; 67 c4.IsValid() == true ? cout << "c4 is right" << endl : cout << "c4 is wrong" << endl; 68 c5.IsValid() == true ? cout << "c5 is right" << endl : cout << "c5 is wrong" << endl; 69 70 return 0; 71 }
priority_queue
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iterator> 2 #include <iostream> 3 #include <queue> 4 #include <algorithm> 5 using namespace std; 6 7 8 int main() 9 { 10 int a[] = {1,2,3,4,5,6,7,8,9,10}; 11 priority_queue<int> pr(a,a+9); 12 pr.push(a[9]); 13 14 cout << "enter queue :"; 15 copy(a,a+10,ostream_iterator<int>(cout,"\t")); 16 cout << endl; 17 18 cout << "leave queue :"; 19 while(!pr.empty()) 20 { 21 cout << pr.top() << "\t"; 22 pr.pop(); 23 } 24 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <queue> 3 #include <string> 4 5 using namespace std; 6 7 class Student 8 { 9 int NO; 10 string name; 11 int chinese; 12 int math; 13 public: 14 Student(int NO,string name,int chinese,int math) 15 { 16 this->NO=NO,this->name=name,this->chinese=chinese,this->math=math; 17 } 18 19 int GetNO() { return NO;} 20 string GetName() { return name;} 21 int GetChinese() const { return chinese; } 22 int GetMath() const { return math; } 23 24 bool operator < (const Student &s) const 25 { 26 int sum1 = chinese + math; 27 int chinese2 = s.GetChinese(); 28 int math2 = s.GetMath(); 29 int sum2 = chinese2 + math2; 30 31 if(sum1 < sum2) 32 return true; 33 if((sum1 == sum2) && (chinese < chinese2)) 34 return true; 35 return false; 36 } 37 }; 38 39 40 int main() 41 { 42 Student s[] = { Student(1001,"zhang",70,80), 43 Student(1002,"li",80,70), 44 Student(1003,"wang",90,85), 45 Student(1004,"zhao",85,75) }; 46 47 48 priority_queue<Student>pr(s,s+4); 49 cout << "Grade sort from high to low:" << endl; 50 cout << "ID\tname\tChinese\tMath" << endl; 51 while(!pr.empty()) 52 { 53 Student t = pr.top(); 54 cout << t.GetNO() << "\t" << t.GetName() << "\t" << t.GetChinese() << "\t" << t.GetMath() << endl; 55 pr.pop(); 56 } 57 58 return 0; 59 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 5 template<class T,class Cont=vector<T>,class Pred=less<typename Cont::value_type> > 6 class FixedPriority : public priority_queue<T,Cont,Pred> 7 { 8 int nLimit; 9 public: 10 FixedPriority(int nLimit) 11 { 12 this -> nLimit = nLimit; 13 } 14 15 void SetLimitSize(int nLimit) 16 { 17 this -> nLimit = nLimit; 18 } 19 20 bool Push(T &t) 21 { 22 if(nLimit > this->size()) 23 { 24 push(t); 25 return true; 26 } 27 return false; 28 } 29 }; 30 31 int main() 32 { 33 FixedPriority<int> fp(10); 34 for(int i = 0 ;i < 15 ;i ++) 35 { 36 if(!fp.Push(i)) 37 cout << "Priority_queue has been full. the " << i << "th element can't insert into" << endl; 38 } 39 40 return 0; 41 }
bitset
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 #include <bitset> 4 5 using namespace std; 6 7 int main() 8 { 9 bitset<5> s1; 10 cout << "initialize memory : " << s1.to_string() << endl; 11 cout << "bit container size: " << s1.size() << "\tset 1 counts:" << s1.count() << endl; 12 13 s1.set(2,true); 14 cout << "After the bit2 set 1 : "; 15 cout << "The memory is :" << s1.to_string() << endl; 16 17 s1[3] = 1; 18 cout << "After the bit3 set 1 : "; 19 cout << "The memory is : " << s1.to_string() << endl; 20 21 s1.set(); 22 cout << "After all the bits set 1 : "; 23 cout << "The memory is : " << s1.to_string() << endl; 24 25 bitset<16> s2(65535); 26 cout << "create bitset via long: " << s2.to_string() << endl; 27 28 bitset<5> s3("1111101",2,5); 29 cout << "create bitset via string : " << s3.to_string() << endl; 30 31 return 0; 32 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 #include <bitset> 4 5 using namespace std; 6 7 8 int main() 9 { 10 bitset<5> s1("01011"); 11 bitset<5> s2("10010"); 12 13 cout << "s1:" << s1.to_string() << "\t"; 14 cout << "s2:" << s2.to_string() << endl; 15 16 s1 &= s2; 17 18 cout << "s1 &= s2: " << s1.to_string() << endl; 19 20 21 bitset<5> s3("01011"); 22 bitset<5> s4("10010"); 23 bitset<5> s5 = s3 & s4; 24 25 cout << "s3:" << s3.to_string() << "\t"; 26 cout << "s4:" << s4.to_string() << endl; 27 28 cout << "s5 = s3 & s4: " << s5.to_string() << endl; 29 cout << "org s3: " << s3.to_string() << endl; 30 31 return 0; 32 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 #include <bitset> 4 5 using namespace std; 6 7 int main() 8 { 9 bitset<8> b("11011101"); 10 cout << "org container b: " << b.to_string() << endl; 11 12 for(int i = 0; i < 4 ;i ++) 13 b.flip(i); 14 cout << "After flip low 4bits : " << b.to_string() << endl; 15 16 return 0; 17 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 #include <bitset> 4 #include <vector> 5 6 using namespace std; 7 8 template<size_t N> 9 class MyAttend 10 { 11 int month; 12 bitset<N> b; 13 public: 14 MyAttend(int month,string strAttend) : month(month),b(strAttend) 15 { 16 ; 17 } 18 19 int GetMonth() { return month; } 20 int GetAttendDays() { return b.count(); } 21 }; 22 23 class Student 24 { 25 string name; 26 vector<MyAttend<31> >v; 27 public: 28 Student(string name) 29 { 30 this -> name = name; 31 } 32 33 void Add(MyAttend<31> &m) 34 { 35 v.push_back(m); 36 } 37 38 void ShowAttendDays() 39 { 40 cout << "name: " << name << endl; 41 cout << "month\texits" << endl; 42 43 for(int i = 0 ;i < v.size();i ++) 44 { 45 MyAttend<31> &m = v.at(i); 46 int month = m.GetMonth(); 47 int days = m.GetAttendDays(); 48 cout << month << "\t" << days << endl; 49 } 50 } 51 }; 52 53 int main() 54 { 55 Student stud1("zhang"); 56 57 string s1 = "1111100111110011111001111100111"; 58 string s2 = "1111100111110011111001111100"; 59 60 MyAttend<31> m1(1,s1); 61 MyAttend<31> m2(2,s2); 62 63 stud1.Add(m1); 64 stud1.Add(m2); 65 66 stud1.ShowAttendDays(); 67 68 return 0; 69 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <fstream> 3 #include <bitset> 4 5 using namespace std; 6 7 template<size_t N> 8 class MyNum 9 { 10 public: 11 bitset<N> b; 12 public: 13 void Set(int ary[],int nSize) 14 { 15 b.reset(); 16 for(int i = 0 ;i < nSize ;i ++) 17 b.set(ary[i]-1,1); 18 } 19 }; 20 21 int main() 22 { 23 int a[6][10] = {{1,2,3,4,5,6,7,8,9,10},{1,3,4,5,6,7,8,9,10,12}, 24 {2,4,6,8,10,13,15,18,19,20},{1,5,6,8,9,10,12,14,18,20}, 25 {3,6,7,10,14,15,16,17,18,19},{1,6,8,9,10,12,15,17,18,19}}; 26 27 ofstream out("a.txt"); 28 29 MyNum<24> m; 30 31 for(int i = 0 ; i < 6 ;i ++) 32 { 33 m.Set(a[i],0); 34 out.write((char *)&m.b,3); 35 cout << i << "\t"; 36 } 37 38 out.close(); 39 40 return 0; 41 42 }
set
map
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #pragma warning(disable : 4786) 2 #include <iostream> 3 #include <sstream> 4 #include <string> 5 #include <vector> 6 #include <map> 7 8 using namespace std; 9 10 class CWord 11 { 12 private: 13 string mainword; 14 vector<string> vecword; 15 public: 16 CWord(string strLine) 17 { 18 istringstream in(strLine); 19 in >> mainword; 20 string mid = ""; 21 while(!in.eof()) 22 { 23 in >> mid; 24 vecword.push_back(mid); 25 } 26 } 27 28 string GetMainWord() { return mainword; } 29 void Show() 30 { 31 cout << endl; 32 cout << "word is :" << "\t" << mainword << endl; 33 cout << "familier word is: " << "\t"; 34 for(int i = 0 ;i < vecword.size(); i ++) 35 cout << vecword[i] << "\t"; 36 cout << endl; 37 } 38 }; 39 40 class CWordManage 41 { 42 multimap<string,CWord> mymap; 43 public: 44 bool Add(string strLine) 45 { 46 CWord word(strLine); 47 pair<string,CWord>p(word.GetMainWord(),word); 48 mymap.insert(p); 49 50 return true; 51 } 52 53 void Show(string strFind) 54 { 55 multimap<string,CWord>::iterator itfind = mymap.find(strFind); 56 if(itfind != mymap.end()) 57 { 58 CWord & obj = (*itfind).second; 59 obj.Show(); 60 } 61 else 62 { 63 cout << strFind << "hasn't fimiliar word in dic." << endl; 64 } 65 } 66 67 void Show() 68 { 69 multimap<string,CWord>::iterator te = mymap.begin(); 70 71 while(te != mymap.end()) 72 { 73 CWord &obj = (*te).second; 74 obj.Show(); 75 te ++; 76 } 77 } 78 }; 79 80 int main() 81 { 82 string s[5] = { string("one single unique"),string("correct true right"), 83 string("near close"),string("happy please"),string("strong powerful")}; 84 85 CWordManage manage; 86 87 for(int i = 0 ; i < 5; i++) 88 manage.Add(s[i]); 89 90 manage.Show(); 91 92 cout << "***************************************************" << endl; 93 manage.Show("near"); 94 cout << "***************************************************" << endl; 95 manage.Show("good"); 96 97 return 0; 98 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #pragma warning(disable:4786) 2 #include <iostream> 3 #include <string> 4 #include <set> 5 6 using namespace std; 7 8 class CEmployee 9 { 10 private: 11 string name; 12 string departname; 13 public: 14 CEmployee(string name,string departname) 15 { 16 this -> name = name; 17 this -> departname = departname; 18 } 19 20 bool operator < (const CEmployee &e) const 21 { 22 bool mark = (departname.compare(e.departname) < 0) ? true : false; 23 24 if(departname.compare(e.departname) == 0) 25 mark = (name.compare(e.name) < 0) ? true : false; 26 27 return mark; 28 } 29 30 string GetName() { return name; } 31 string GetDepart() { return departname; } 32 }; 33 34 class CManage 35 { 36 multiset<CEmployee> myset; 37 public: 38 bool Add(CEmployee &e) 39 { 40 myset.insert(e); 41 return true; 42 } 43 44 void Show() 45 { 46 multiset<CEmployee>::iterator te = myset.begin(); 47 48 while(te != myset.end()) 49 { 50 CEmployee &obj = *te; 51 cout << obj.GetDepart() << "\t" << obj.GetName() << endl; 52 te ++; 53 } 54 } 55 }; 56 57 58 int main() 59 { 60 CEmployee e1("zhangdan","renli"); 61 CEmployee e2("zhouqi","zhuangpei"); 62 CEmployee e3("wangwu","zhizao"); 63 CEmployee e4("zhaoliu","zhizao"); 64 CEmployee e5("lisi","zhuangpei"); 65 CEmployee e6("tianjiu","zhizao"); 66 67 CManage manage; 68 manage.Add(e1); 69 manage.Add(e2); 70 manage.Add(e3); 71 manage.Add(e4); 72 manage.Add(e5); 73 manage.Add(e6); 74 75 manage.Show(); 76 77 return 0; 78 }
STL还有一些预迭代器:
1,插入迭代器
back_insert_iterator(Cont &x)
front_insert_iterator(Cont &x)
insert_iterator(Cont &x,Cont::iterator it)
back_insert_iterator<Cont> back_inserter(Cont &x)
front_insert_iterator<Cont> frontinserter(Cont &x)
例子:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <list> 3 #include <iterator> 4 5 using namespace std; 6 7 void display(list<int> &v) 8 { 9 for(list<int>::iterator it = v.begin() ; it != v.end() ; it ++) 10 cout << *it << "\t"; 11 cout << endl; 12 } 13 14 15 int main() 16 { 17 list<int> v; 18 19 back_insert_iterator<list<int> > backit(v); 20 21 *backit ++ = 1; 22 *backit ++ = 2; 23 24 display(v); 25 26 *back_inserter(v) = 3; 27 *back_inserter(v) = 4; 28 29 display(v); 30 31 front_insert_iterator<list<int> > frontit(v); 32 33 *frontit ++ = 5; 34 *frontit ++ = 6; 35 36 display(v); 37 38 *front_inserter(v) ++ = 7; 39 *front_inserter(v) ++ = 8; 40 41 display(v); 42 43 list<int>::iterator it = v.begin(); 44 for(int i = 0 ;i < 3 ;i ++) 45 { 46 it ++; 47 } 48 49 insert_iterator<list<int> >insertit(v,it); 50 *insertit ++ = 9; 51 52 display(v); 53 54 return 0; 55 }
2,逆向迭代器
reverse_iterator(Ranit x)
reverse_bidirectional_iterator(Bidit x)
例子:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <list> 3 #include <vector> 4 #include <iterator> 5 6 using namespace std; 7 8 template<class reverse_iter> 9 void reverse_display(reverse_iter first,reverse_iter last) 10 { 11 while(first != last) 12 { 13 cout << *first << "\t"; 14 first ++; 15 } 16 17 cout << endl; 18 } 19 20 int main() 21 { 22 vector<int> v; 23 list<int> l; 24 25 for(int i = 1 ;i <= 5; i ++) 26 { 27 v.push_back(i); 28 l.push_back(i+5); 29 } 30 31 cout << "display vector reversely: " << endl; 32 reverse_iterator<vector<int>::iterator,int> first(v.end()); 33 reverse_iterator<vector<int>::iterator,int> last(v.begin()); 34 reverse_display(first,last); 35 36 cout << "display list reversely: " << endl; 37 reverse_bidirectional_iterator<list<int>::iterator,int> first2(l.end()); 38 reverse_bidirectional_iterator<list<int>::iterator,int> last2(l.begin()); 39 reverse_display(first2,last2); 40 41 return 0; 42 }
3, 迭代器函数
template<class InIt,class Dist>
void advance(Init & it, Dist n); it += n
template<class Init,class Dist>
ptrdiff_t distance(Init first,Init last) 求距离
例子:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <list> 3 #include <algorithm> 4 5 using namespace std; 6 7 int main() 8 { 9 int a[] = {1,2,3,4,5,6}; 10 11 list<int> l(a,a+6); 12 13 cout << "The element in List: "; 14 copy(l.begin(),l.end(),ostream_iterator<int>(cout,"\t")); 15 cout << endl; 16 17 list<int>::iterator mid = find(l.begin(),l.end(),3); 18 19 cout << "Element 3's position : " << distance(l.begin(),mid) << endl; 20 21 advance(mid,2); 22 23 cout << "Element 3 's ahead 2 is : " << *mid << endl; 24 25 return 0; 26 }