C++ Lambda Expression returning the number of vector elements that begin with a given letter.

Description

C++ Lambda Expression returning the number of vector elements that begin with a given letter.

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

int main()// www  .  ja  v  a  2  s  .  c  om
{
  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";
}



PreviousNext

Related