c++ - How to use std::toupper in std::for_each? -
i'm trying convert lowercase characters of string uppercase counterpart using std::toupper function , i'm using std::for_each algorithm iterate on characters in string.
#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); }
when compile code i'm getting error:
in file included /usr/include/c++/4.8/algorithm:62:0, 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 here /usr/include/c++/4.8/bits/stl_algo.h:4417:14: error: invalid conversion ‘char’ ‘std::basic_string<char>*’ [-fpermissive] __f(*__first); ^
what proper way of character conversion lowercase uppercase using std::toupper , std::for_each?
a string
container of char
s, basically. when iterate of string
, going 1 char
@ time. functor pass for_each
called char
, not string*
, hence error:
invalid conversion ‘char’ ‘std::basic_string<char>*
the correct implementation be:
std::for_each(x.begin(), x.end(), std::toupper);
that, however, nothing. return value of toupper
ignored, , function has no side effects. if wanted transform string upper case version, have use std::transform
:
std::transform(x.begin(), x.end(), x.begin(), std::toupper);
or, provde locale:
char locale_upper(char c) { return std::toupper(c, std::locale()); } std::transform(x.begin(), x.end(), x.begin(), locale_upper);
or, in c++11:
std::transform(x.begin(), x.end(), x.begin(), [](char c){ return std::toupper(c, std::locale()); });
at point might use for
-loop:
for (char& c : x) { c = std::toupper(c, std::locale()); }
Comments
Post a Comment