A lambda expression finding the largest even number in a vector - C++ STL

C++ examples for STL:Lambda

Description

A lambda expression finding the largest even number in a vector

Demo Code

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

int main()/*www  .  jav a 2  s  .com*/
{
  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;
}

Result


Related Tutorials