該問題歸結為std::transform函數的使用
函數原型
template < class InputIterator, class OutputIterator, class UnaryOperator >
OutputIterator transform ( InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperator op );
template < class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperator >
OutputIterator transform ( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperator binary_op );
說明:
對於第一個原型:函數將對從輸入參數的first1-last1的全部變量做op函數操作。結果保存到result中,或是通過返回值返回。
對於原形二:這個是對一的一個擴展,對於1這個只能對單個元素隊列進行op操作,而第二個原形則是對對first1-last1上的元素和first2開始序列的元素逐個binary_op計算再保存到結果
示例
int op_inc(int num) { return ++i; }
int op_sum(int numa,int numb) { return a+b; }
int main()
{
vector<int >first;
vector<int >second;
vector<int >result;
.........//初始化過程省略,不過要注意當調用第二個原型的時候,保持隊列二的長度要大於等於1
transform(first.begin(), first.end(), result.begin(), op_inc);
transform(first.begin(), first.end(), second.begin(), result.begin(), op_sum);
........//輸出結果
return 0;
}
以上是transform的基本使用,接下來說明如何用它來處理字符串的大小寫轉換
事實上很簡單,主要用到了,單個字符的大小寫轉換函數:tolower(),toupper()
不過對於大寫轉小寫,同時小寫轉大寫的要自己單獨處理,函數如下
char exchange(char c)
{
if(c <= 'Z' && c >= 'A')
c = tolower(c);
else if(c >= 'a' && c <= 'z')
c = toupper(c);
return c;
}
示例
std::string str = "Http";
transform(str.begin(), str.end(), str.begin(), ::tolower); //將大寫的都轉換成小寫
transform(str.begin(), str.end(), str.begin(), ::toupper); //將小寫的都轉換成大寫
transform(str.begin(), str.end(), str.begin(), exchange); //大小寫切換
注以上結果都保存在str中。