A lambda expression returning the number of vector elements that begin with a given letter. - C++ STL

C++ examples for STL:Lambda

Description

A lambda expression returning the number of vector elements that begin with a given letter.

Demo Code

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using std::string;

int main()/*from   w ww  .ja  v a  2s .c  o  m*/
{
  std::vector <string> words {"apple", "pear", "plum", "orange", "peach", "grape", "greengage"};

  std::cout << "Words are:\n";

  for (auto word : words)
    std::cout << std::setw(10) << word;

  std::cout << std::endl;

  auto count = [&words](char letter){
                                      int n {};
                                      for (auto& word : words){
                                          if (letter == word[0])
                                             ++n;
                                      }
                                      return n;
                                    };
  char ch {'p'};
  std::cout << "There are " << count(ch) << " words beginning with " << ch << ".\n";
  ch = 'g';
  std::cout << "There are " << count(ch) << " words beginning with " << ch << ".\n";
}

Result


Related Tutorials