1. 程式人生 > >STL源碼 學習

STL源碼 學習

lar point msi pla ted printf function 標準庫 c++語言

1、STL<sstream>庫:使用string代替字符數組,避免緩沖區溢出;傳入參數和返回值類型可自動推導出來,避免類型轉換錯誤

istream、ostream、stringstream分別進行流的輸入、輸出和輸入輸出操作;stringstream構造和析構函數耗CPU時間,最好重復使用,clear()清除

string s = "100000";

int n = 0;

stream << s;

stream >> n; // n等於100000.

template <class T>
void to_string(string &res, const T &t) {
  ostringstream oss;
  oss 
<< t; res = oss.str(); }
sstream庫中getline()函數
istream& getline (char* s, streamsize n ); istream& getline (char* s, streamsize n, char delim );

Extracts characters from the stream as unformatted input and stores them into s as a c-string, until either the extracted character is the delimiting character

, or n characters have been written to s (including the terminating null character). 抽取輸入,存儲為const string,直到所抽取的字符被分隔,如‘\n’,或者已有n個字符被存儲(包括‘\0‘)。

 1 #include<iostream>
 2 #include<sstream>
 3 using namespace std;
 4 
 5 // main function
 6 int main() {
 7   stringstream ss_stream;
 8   int first, second;
9 ss_stream << "456"; 10 ss_stream >> first; 11 cout << first << endl; 12 // 註意clear()清除管道已有數據 13 ss_stream.clear(); 14 ss_stream << true; 15 ss_stream >> second; 16 cout << second << endl; 17 18 ss_stream.clear(); 19 ss_stream << "字符串一" << endl; 20 ss_stream << "字符串二" << endl; 21 ss_stream << "字符串三" << endl; 22 ss_stream << "字符串四" << endl; 23 24 // char buffer[100]; // 聲明未初始化 25 // while (ss_stream.getline(buffer, sizeof(buffer))) { 26 // printf("msg=%s\n", buffer); 27 // } 28 29 string stemp; 30 while (getline(ss_stream, stemp)) { 31 cout << stemp << endl; 32 } 33 return 0; 34 }

2、C++類模板 template <class T>

模板是泛型編程的基礎,類是對象的抽象,模板是類的抽象,用模板能定義出具體類。屬於編譯時的多態,體現在參數的多態。

使用:template <class T> // 帶參數T的類模板

 1 #include<iostream>
 2 #include<cmath>
 3 using namespace std;
 4 
 5 // the declaration of class template
 6 template<class T>
 7 class Point {
 8  public:
 9   Point(T = 0, T = 0);  // 類的構造函數
10   Point(Point&);        // 類的拷貝構造函數
11   T Distance(Point&);   // 返回類型T的成員函數
12  private:
13   T x, y;
14 };
15 
16 // The implementation of class template Point
17 template <class T>
18 Point<T>::Point(T a, T b) : x(a), y(b){}
19 
20 template <class T>
21 Point<T>::Point(Point& a) {
22   x = a.x;
23   y = a.y;
24 }
25 
26 template <class T>
27 T Point<T>::Distance(Point &a) {
28   return sqrt((x - a.x)*(x - a.x) + (y - a.y) * (y - a.y));
29 }
30 
31 // main function
32 int main() {
33   Point<int> a1(3, 4), a2(5, 6);
34   cout << "The distance of these two points: "<< a1.Distance(a2) << endl;
35   
36   Point<double> b1(7.8, 9.8), b2(34.8, 25.4);
37   cout << "The distance of these two points: "<< b1.Distance(b2) << endl;
38   return 0;
39 }

3、cmath是c++語言中的庫函數,其中的c表示函數是來自c標準庫的函數,math為數學常用庫函數。編譯時必須加上參數「-lm」。

STL源碼 學習