#include <string>
#include <algorithm>
std::string& relabel(std::string &str)
{
char c;
c = str[0];
std::replace(str.begin(), str.end(), c, 'a');
std::replace(str.begin(), str.end(), str[1], 'b');
return str;
}
relabel(std::string("123321")),返回值是"ab332a"。
第一句std::replace()將兩個'1'改爲'a';第二句std::replace()只將第一個'2'改爲'b',第二個'2'仍保持原樣,不符合調用目的。
注意:模板函數類似宏替換,如果實參的值在調用過程中被改變,有可能達不到調用模板函數的目的。但是有時這種替換又很有用,例如str.end()這樣可以根據str動態變化的。