Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ STL 中做元素替換的強力函式 replace

學 STL 的目的是讓程式碼更簡單,而不是更複雜。以字元替換為例,不必自己動手寫迴圈,replace 就能勝任。它的宣告如下:

template<class FwdIt, class T>
void replace(FwdIt first, FwdIt last,
             const T& vold, const T& vnew);

使用前需引入標頭檔:

#include <algorithm>
using namespace std;

實作範例

以下示範如何依據目前字元,對字串後半段進行互換:

for (int i = 0; i < (int)strReplace.size(); i++) {
    if ('0' == strReplace[i]) {
        replace(strReplace.begin() + i, strReplace.end(), '1', '3');
        replace(strReplace.begin() + i, strReplace.end(), '3', '1');
    }
    if ('3' == strReplace[i]) {
        replace(strReplace.begin() + i, strReplace.end(), '0', '2');
        replace(strReplace.begin() + i, strReplace.end(), '2', '0');
    }
}

兩次互換的寫法可以完成「交換」而非單向取代的效果,不必自己實作。當然,若你是 C/C++ 初學者,或正在準備面試、筆試,自己寫一遍是很好的練習;但日常開發中直接用標準庫提供的工具,才是更務實的選擇。

Copyright © Linux教程網 All Rights Reserved