We’re going to build up to using functors and λ-expressions.
char embiggen(char c) { if ('a' <= c && c <= 'z') return c - 'a' + 'A'; else return c; } int main() { string name = "Beverly Hills Chihuahua"; for (char &c : name) // & for reference c = embiggen(c); cout << name << '\n'; }
BEVERLY HILLS CHIHUAHUA
Use a ternary expression, instead:
char embiggen(char c) { return ('a'<=c && c<='z') ? c-'a'+'A' : c; } int main() { string name = "Beverly Hills Chihuahua"; for (char &c : name) c = embiggen(c); cout << name << '\n'; }
BEVERLY HILLS CHIHUAHUA
Use the transform
algorithm, rather than an explicit loop:
char embiggen(char c) { return ('a'<=c && c<='z') ? c-'a'+'A' : c; } int main() { string name = "Beverly Hills Chihuahua"; string result = name; // Why? transform(name.begin(), name.end(), result.begin(), embiggen); cout << result << '\n'; }
BEVERLY HILLS CHIHUAHUA
This example uses the same buffer for input & output of transform
.
char embiggen(char c) { return ('a'<=c && c<='z') ? c-'a'+'A' : c; } int main() { string name = "Beverly Hills Chihuahua"; transform(name.begin(), name.end(), name.begin(), embiggen); cout << name << '\n'; }
BEVERLY HILLS CHIHUAHUA
This code uses an actual functor, as opposed to a function.
class embiggen { public: char operator()(char c) { return ('a'<=c && c<='z') ? c-'a'+'A' : c; } }; string name = "Beverly Hills Chihuahua"; embiggen biggifier; transform(name.begin(), name.end(), name.begin(), biggifier); cout << name << '\n';
BEVERLY HILLS CHIHUAHUA
Create a temporary functor object:
class embiggen { public: char operator()(char c) { return ('a'<=c && c<='z') ? c-'a'+'A' : c; } }; string name = "Beverly Hills Chihuahua"; transform(name.begin(), name.end(), name.begin(), embiggen()); cout << name << '\n';
BEVERLY HILLS CHIHUAHUA
Instead of a functor, a lambda-expression can also be used.
string name = "Beverly Hills Chihuahua"; transform(name.begin(), name.end(), name.begin(), [](char c){ return 'a'<=c && c<='z' ? c-'a'+'A' : c; } ); cout << name << '\n';
BEVERLY HILLS CHIHUAHUA
Don’t re-invent the wheel:
string name = "Beverly Hills Chihuahua"; for (char &c : name) c = toupper(c); cout << name << '\n';
BEVERLY HILLS CHIHUAHUA