程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> STL簡介

STL簡介

編輯:關於C++

前言

本篇文章是作者本人使用STL 後的一些看法, 對於想要靠此文章學習STL, 是不可能的. 建議三後面介紹的一些書入門.

STL的概念

在STL 中, 大至上分三個主要的功能. 分別是collect class, (例如 vector ,list , .....), 算法部份(如sort ,find ...), 最是一些工具(如auto_ptr , make_pair ....), 其中以collect class 和算法部份最為重要.

STL 使用一種稱作 iterator (中文有人翻作泛型指標) 的資料類型來連接collect class 和算法部份. 為了達到能夠重復使用算法和collect class. 在STL 中把這些東西更進一步抽象化. 因此STL訂義了一堆抽象化的行為稱作concept. 您可以想像concept 是在說明一些行為. 只要某一個型別合乎concept 中說明的行為. 就說此類型具有此concept.

舉例說明, 如有concept C1,C2. 算法A1, A2. 資料類型D1 具有C1 的行為,D2 有C1,C2.

如A1 要求需要具有C1 的型別. 則任何一個有C1 的資料類型都可以給A1 使用. 在此例中有D1和D2.

如A2 要求具有C1跟C2的型別. 在此只有D2 可以給A2 使用.

STL 使用抽象化的行為定義且實作它們, 來達到算法和資料類型的重復使用.

iterator 在STL 中是很重要的一個概念, iterator 和C 的point 很相, 但他不是指標(note 在某一些狀況下iterator 是以C 的point 來實作). 他提供類似point 的功能, 如 '++' 運算表示把iterator 移到下一個element , '*' 運算表示存取iterator 目前指向的element (在此使用'指向'並不是很好). 利用iterator 你可以走訪整個collect 中存放的內容.

舉個例子說明iteraotr 的功能吧.

vector 是STL 中眾多的collect class 中的一種. vector 提供begin() 和end() 這類的member function 來取得vector 中第一個element 的iterator, 和最後一個element的下一個element. 您可以這樣使用:

std::vector<int> vtInt;
vtInt.push_back(1);
...
.. // 假設對vtInt 做了很多不同的動做, 如push_back ...
std::vector<int>::iterator itBegin=vtInt.begin();
std::vector<int>::iterator itEnd=vtInt.end();
for( ; itBegin != itEnd ;++itBegin) // 走訪itBegin 到 itEnd 不含itEnd 之間的所有element
{
int x=*itBegin; // 取得itBegin 指向的資料
*itBegin = .... ; // 存放資料到itBegin 指向的資料
}

由此例中iterator 有和C point 類似的功能.

機乎所有的STL 的算法都會要求輸入的資料是itearot 如sort 算法, 要求輸入兩個iterator , 然後把這兩個iterator 之間的資料加以排序. 介由引進iterator , sort 可以排序的東西就變多了.

使用范例

I. 在STL 中使用標准輸出. Say Hello

#include <iostream> // STL 的輸入輸出包含檔. 在STL 中都沒有使用.h or .hpp 等副檔名
int main(int argc,char* argv[])
{
std::cout << "Hello!! This is STL " << std::endl; // 使用stl 的標准輸出, std 是STL 的namespace 所以要這樣用std::cout
return 0;
}

II. 從標准輸入讀入字串, 排序後再輸出

#include <iostream> // STL 的輸入輸出包含檔
#include <algorithm> // STL 的算法包含檔
#include <string> // STL 的字串
#include <vector> // STL 的一個collect class 這是一個像陣列的class
const int d_nReadLine=5;
int main(int argc,char* argv[])
{
std::vector<std::string> vtString; // 宣告一個字串vector
std::string strTemp; // 宣告一個字串
for( int i = 0 ; i < d_nReadLine ; i++) // 讀取d_nReadLine 個字串並將結果存到vtString 中
{
std::cin >> strTemp; // 讀入字串
vtString.push_back(strTemp); // 將讀入的字串存到vtString 的最後面
}
std::sort(vtString.begin(),vtString.end()); // 將vtString 中得資料sort
std::copy(vtString.begin(),vtString.end(),
std::ostream_iterator<std::string>(std::cout,"\n")); // 將vtString 中得資料輸出
return 0;
}

note :

std::sort 和std::copy 都是STL 提供的算法.

參考書籍

泛型程式設計與STL, Generic Programming and the STL. Matthew H. Austern 著, 侯捷/黃俊堯 譯

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved