C++ Lambda Expression finding the largest even number in a vector

Description

C++ Lambda Expression finding the largest even number in a vector

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

int main()//from ww w  .  ja v  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;
}



PreviousNext

Related