您的位置:首页 > 编程语言 > C语言/C++

(原創) 如何將container中的iterator,從一個值取代成另外一個值? (C/C++) (STL)

2007-04-19 15:33 766 查看
Abstract
若想將container中的iterator,從一個值取代成另外一個值,但container並沒有提供replace()這個member function,而是提供了replace()這個Generic Algorithm。

Introduction
以下範例我們將vector中,所有的1取代成4。

1#include <iostream>
10#include <vector>
11#include <algorithm>
12#include <sstream>
13
14using namespace std;
15
164
2
3

19行的

replace(ivec.begin(), ivec.end(), 1, 4);

第一個參數傳入vector的起始位址,第二個參數傳入vector的結束位址,第三個參數是要被取代的值,第四個參數是要取代成的值。

replace()完整的定義為

template<typename ForwardIterator, typename T>
void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value);

其他相關的algorithm還有replace_if(),replace_copy(),replace_copy_if()。

Conclusion
初學者學習STL,對於STL的container僅提供有限的功能感到困擾,因為STL是基於泛型(GP : Generic Programming)下的產物,和物件導向的.NET Framework、Java SDK不同。在物件導向下,algorithm和container綁在一起,每個container都自給自足的提供自己的algorithm(member function),但這樣的缺點是,很多container都必須提供相同的基礎功能,這樣會造成class的肥大,且要重複寫相同的功能,如vector需提供replace(),那list、deque、stack怎麼辦?也要重新寫replace()嗎?泛型強調algorithm和container分離,而algorithm可以支援各種container,對於開發STL的人員來說,只要開發一次replace()即可,對於使用STL的人員來說,也只要學習一次replace()即可,而且將來若要從vector改成list,只需換掉container即可,其他程式都不須修改。

所以使用STL時,若container沒有提供適當的功能,別忘了找找Generic Algorithm,也可順便欣賞這個由GP思維下library的beauty。

Reference
Matthew H. Austern. Generic Programming and the STL. Addision Wesely, 1998.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: