使用for_each和tolower()

时间:2012-02-17 03:05:02

标签: c++ stl foreach g++ stl-algorithm

我正在尝试使用STL函数for_each将字符串转换为小写,我不知道我做错了什么。这是有问题的for_each行:

clean = for_each(temp.begin(), temp.end(), low);

其中temp是一个包含字符串的字符串。这是我写的低功能:

void low(char& x)
{
x = tolower(x);
}

我不断得到的编译错误就是这样:

error: invalid conversion from void (*)(char&) to char [-fpermissive]

我做错了什么?

编辑: 这是我写的整个函数:

void clean_entry (const string& orig, string& clean)
{
string temp;
int beginit, endit;

beginit = find_if(orig.begin(), orig.end(), alnum) - orig.begin();
endit = find_if(orig.begin()+beginit, orig.end(), notalnum) - orig.begin();

temp = orig.substr(beginit, endit - beginit);

clean = for_each(temp.begin(), temp.end(), low);
}

2 个答案:

答案 0 :(得分:6)

您尝试做的标准习惯是

#include <algorithm>
#include <string> 

std::string data = "Abc"; 
std::transform(data.begin(), data.end(), data.begin(), ::tolower);

答案 1 :(得分:2)

for_each的返回值是您传递的函数 - 在本例中为low。所以这个:

clean = for_each(temp.begin(), temp.end(), low);

相当于:

for_each(temp.begin(), temp.end(), low);
clean = low;

当你真正想要的可能是这样的时候:

for_each(temp.begin(), temp.end(), low); // note: modifies temp
clean = temp;

(或者您可以先删除temp,然后在整个过程中使用clean

相关问题