C++ vector search via lambda expression

Description

C++ vector search via lambda expression

#include <iostream>
#include <iomanip>
#include <vector>

int main()//from ww w  .j av  a2  s  .  c  o m
{
  std::vector <int> numbers {11, 21, 41, 116, -14, 15, 16, 13, 123};

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

  for (auto n : numbers)
    std::cout << std::setw(5) << n;

  std::cout << std::endl;

  auto largest_even = [](std::vector<int>& v){
                                                  int largest {};
                                                  bool found {false};
                                                  for (auto n : v){
                                                        if (!found && n % 2 == 0)
                                                        {
                                                              largest = n;
                                                              found = true;
                                                        }
                                                        else
                                                        {
                                                              if (found && n % 2 == 0 && largest < n)
                                                                largest = n;
                                                        }
                                                  }
                                                  return largest; };

  std::cout << "Largest even number is " << largest_even(numbers) << std::endl;
}
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using std::string;

int main()/*from  w  w  w  . ja  va  2s  . 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