點(diǎn)睛之筆:使用STL的最高境界就是程式看不到for和while loop,完全用STL 的algorithm搞定。
下例中我們需要將vector中的所有字符串變成小寫,使用transfor()對vector中的每個(gè)string元素做處理,C\C++的字符串沒有提供轉(zhuǎn)寫小寫的功能,但是C中有對每個(gè)字符轉(zhuǎn)寫小寫的功能。猶豫string也是個(gè)container,我們需要再次使用transform()來處理每個(gè)字符,并且使用<cctype>中的tolower()將每個(gè)字符改成小寫。
09 #include <iostream>
10
#include <cctype>
11
#include <algorithm>
12
#include <vector>
13
#include <string>
14
15
using namespace std;
16
17
string& toLower(string&);
18
19
int main() {
20
vector<string> svec;
21
svec.push_back("Stanley B. Lippman");
22
svec.push_back("Scott Meyers");
23
svec.push_back("Nicolai M. Josuttis");
24
25
// Modify each string element
26
transform(svec.begin(), svec.end(), svec.begin(), toLower);
27
28
copy(svec.begin(),svec.end(), ostream_iterator<string>(cout,"\n"));
29
30
return 0;
31
}
32
33
string& toLower(string& s) {
34
// Modify each char element
35
transform(s.begin(), s.end(), s.begin(), tolower);
36
return s;
37
}
補(bǔ)充:transform是遍歷一個(gè)容器里面的元素然后執(zhí)行一個(gè)操作。
參數(shù)1和參數(shù)2是數(shù)據(jù)起始和結(jié)束位置(迭代器,也可以是string)
如:string s="hello"; transform(s.begin(),s.end(),s.begin(),toupper);
參數(shù)3是寫入目標(biāo)的起始位置;
參數(shù)4是執(zhí)行的操作(函數(shù))。
思想2:
實(shí)例:#include<iostream>
using namespace std;
int my_toupper(int ch)
{
if(ch>='a'&&ch<='z')
{
return ch-(int('a')-int('A'));
}
else
{
return ch;
}
}
int my_tolower(int ch)
{
if(ch>='A'&&ch<='Z')
{
return ch+(int('a')-int('A'));
}
else
{
return ch;
}
}
int main()
{
char buf[]="abc123ABC";
char *p=buf;
while(*p!='\0')
{
cout<<(char)my_toupper(*p)
<<","
<<(char)my_tolower(*p)
<<endl;
++p;
}
return 0;
}
思路3:
posted on 2012-04-06 09:14
憤怒的考拉 閱讀(312)
評論(0) 編輯 收藏