CS253: Software Development with C++

Spring 2018

Functor Example

See this page as a slide show

CS253 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 #2

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 #3

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 #4

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 #5

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 #6

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 #7

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 #8

Don’t re-invent the wheel:

string name = "Beverly Hills Chihuahua";

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

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

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:52

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building