C++ articles:Guru of the Week #3:使用標準庫 (轉)
作者:Hub Sutter
譯者:plpliuly
/*此文是譯者出於自娛翻譯的GotW(Guru of the Week)系列文章第3篇,原文的版權是屬於Hub Sutter(著名的C++專家,"Exceptional C++"的作者)。此文的翻
譯沒有徵得原作者的同意,只供學習討論。——譯者
*/
#3 使用標準庫
難度:3/10
使用標準庫提供的演算法比你自己手工寫一個要方便的多。仍然以GotW #2中討論的定義為例子,我們將看到如果直接使用標準庫將會避免很多問題。
問題:
如果我們用標準庫中的已有演算法代替GotW#2中的最初程式碼中的迴圈,有哪些問題可以自然避免?(注意:與以前一樣,不能改變函式的語義。)
GotW #2中的問題回顧:
最初的實現:
string FindAddr( list
{
for( list
i != l.end();
i++ )
{
if( *i == name )
{
return (*i).addr;
}
}
return "";
}
經過修改後,除了l.end()依然是每次迴圈到要,其餘的不足之處均已修改(譯者:請參看GotW #2):
string FindAddr( const list
const string& name )
{
string addr;
for( list
i != l.end();
++i )
{
if( (*i).name == name )
{
addr = (*i).addr;
break;
}
}
return addr;
}
答案:
在最初的程式碼基礎上,僅僅用find()代替迴圈而不做任何其他的修改就可以避免兩個不必要臨時而且可以幾乎把初始程式碼中的對l.end()的冗餘呼叫全部
去掉:
string FindAddr( list
{
list
find( l.begin(), l.end(), name );
if( *i != l.end() )
{
return (*i).addr;
}
return "";
}
再結合我們在GotW #2中提到的修改方法,最終可以得到如下程式碼:
string FindAddr( const list
const string& name )
{
string addr;
list
find( l.begin(), l.end(), name );
if( i != l.end() )
{
addr = (*i).addr;
}
return addr;
}
[忠告]儘量使用標準庫演算法,因為那樣比自己手動重新寫一個演算法要快捷,而且不易出錯。
(結束)
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-988190/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- C++ articles:Guru of the Week #1 (轉)C++
- C++ articles:Guru of the Week #4 -- Class Mechantics (轉)C++
- Guru of the week:#18 迭代指標. (轉)指標
- Guru of the week:#17 型別對映. (轉)型別
- Guru of the week:#19 自動型別轉換. (轉)型別
- Guru of the Week 條款19:自動轉換 (轉)
- Guru of the Week 條款27:轉呼叫函式 (轉)函式
- C++標準庫C++
- Guru of the Week 條款28:“Fast Pimpl”技術 (轉)AST
- Guru of The week #20 程式碼的複雜性 Ⅰ. (轉)
- Guru of the Week 條款09:記憶體管理(上篇) (轉)記憶體
- Guru of the Week 條款10:記憶體管理(下篇) (轉)記憶體
- Guru of the Week 條款24:編譯級防火牆 (轉)編譯防火牆
- Guru of the Week 條款30附錄:介面原則 (轉)
- Guru of the Week 條款05:覆寫虛擬函式 (轉)函式
- Guru of the Week 條款13:物件導向程式設計 (轉)物件程式設計
- Guru of the Week #5:虛擬函式的重新定義 (轉)函式
- c/c++ 標準庫 vectorC++
- C++標準模板庫------容器C++
- C++標準庫::拾遺C++
- Guru of the Week 條款07:編譯期的依賴性 (轉)編譯
- Guru of the Week 條款11:物件等同(Object Identity)問題 (轉)物件ObjectIDE
- Guru of the Week 條款14:類之間的關係(上篇) (轉)
- Guru of the Week 條款15:類之間的關係(下篇) (轉)
- C++ 標準庫 std::set std::multiset swap()的使用C++
- C++標準庫簡介、與STL的關係【轉】C++
- C++標準庫有四種智慧指標C++指標
- C++標準庫標頭檔案介紹C++
- 標準模板庫STL (轉)
- c/c++ 標準庫 map set 插入C++
- c/c++ 標準庫 迭代器(iterator)C++
- C++ 標準庫-字串 string 類C++字串
- C++標準庫名字和標頭檔案--表C++
- CUJ:標準庫:標準庫中的搜尋演算法 (轉)演算法
- 標準模板庫介紹(轉)
- C++ 及標準庫中的那些大坑C++
- c++標準程式庫:STL容器之mapC++
- Guru of the Week 條款16:具有最大可複用性的通用Containers (轉)AI