Cope an array into a vector using a lambda function. - C++ STL

C++ examples for STL:Lambda

Description

Cope an array into a vector using a lambda function.

Demo Code

#include <algorithm>
#include <array>
#include <cstdint>
#include <functional>
#include <iostream>
#include <typeinfo>
#include <vector>

using MyArray = std::array<int, 5>;
using MyVector = std::vector<MyArray::value_type>;

void PrintArray(const std::function<void(MyArray::value_type)>& myFunction)
{
    MyArray myArray{ 1, 2, 3, 4, 5 };//  w w w . j  a v  a 2s. co m

    std::for_each(myArray.begin(),
        myArray.end(),
        myFunction);
}

int main()
{
    MyVector myCopy;
    auto myClosure = [&myCopy](const MyArray::value_type& number) {
            std::cout << number << std::endl;
            myCopy.push_back(number);
        };
    std::cout << typeid(myClosure).name() << std::endl;

    PrintArray(myClosure);

    std::cout << std::endl << "My Copy: " << std::endl;
    std::for_each(myCopy.cbegin(),
        myCopy.cend(),
        [](const MyVector::value_type& number){
            std::cout << number << std::endl;
        });

    return 0;
}

Result


Related Tutorials