如何在std :: for_each中使用std :: toupper?

时间:2015-05-15 03:20:04

标签: c++ c++11 stl

我尝试使用std :: toupper函数将字符串的小写字符转换为大写字母,并且我使用std :: for_each算法迭代字符串中的字符。

#include <iostream>
#include <string>
#include <algorithm>
#include <locale>

std::string convert_toupper(std::string *x) {
  return std::toupper(*x, std::locale());
}

int main() {
  std::string x ("example");

  std::for_each(x.begin(), x.end(), convert_toupper);
}

当我编译此代码时,我收到此错误:

In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from me2.cpp:3:
/usr/include/c++/4.8/bits/stl_algo.h: In instantiation of ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >; _Funct = std::basic_string<char> (*)(std::basic_string<char>*)]’:
me2.cpp:13:52:   required from here
/usr/include/c++/4.8/bits/stl_algo.h:4417:14: error: invalid conversion from ‘char’ to ‘std::basic_string<char>*’ [-fpermissive]
  __f(*__first);
              ^

使用std :: toupper和std :: for_each将字符从小写转换为大写的正确方法是什么?

2 个答案:

答案 0 :(得分:4)

string基本上是char s的容器。当您迭代string时,您一次只能charfor_each。因此,传入char的仿函数将使用string*调用,而不是invalid conversion from ‘char’ to ‘std::basic_string<char>* ,因此错误:

std::for_each(x.begin(), x.end(), std::toupper);

正确的实施只是:

toupper
然而,那不会做任何事情。 std::transform(x.begin(), x.end(), x.begin(), std::toupper); 的返回值将被忽略,该函数没有副作用。如果您真的希望字符串转换为大写版本,则必须使用std::transform

char locale_upper(char c) { return std::toupper(c, std::locale()); }
std::transform(x.begin(), x.end(), x.begin(), locale_upper);

或者,提供区域设置:

std::transform(x.begin(), x.end(), x.begin(), [](char c){
    return std::toupper(c, std::locale());
});

或者,在C ++ 11中:

for

此时你也可以使用for (char& c : x) { c = std::toupper(c, std::locale()); } - 循环:

{{1}}

答案 1 :(得分:0)

Options -MultiViews RewriteEngine On RewriteBase / RewriteCond %{THE_REQUEST} /tut\.php\?v=(\d+) [NC] RewriteRule ^ /tut/%1? [R=302,L,NE] RewriteRule ^tut/(\d+)/?$ tut.php?v=$1 [QSA,L,NC] 中,您已经将<locale>函数转换为大写的小写字符串。函数调用有点棘手,但它非常紧凑:

std::ctype::toupper