CS253

CS253: Software Development with C++

Spring 2017

Functor Example

See this page as a slide show

Functor Example

Example #1

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

Example #1½

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

Example #2

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

Example #3

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

Example #4

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

Example #5

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

Example #6

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

Example #7

Don’t re-invent the wheel:

string name = "Beverly Hills Chihuahua";

for (char &c : name)
    c = toupper(c);

cout << name << '\n';
BEVERLY HILLS CHIHUAHUA

Modified: 2017-04-14T11:51

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building