Skip to content

Instantly share code, notes, and snippets.

@zacck-zz
Last active November 27, 2019 07:10
Show Gist options
  • Save zacck-zz/e6e6fbd91233db4d6d8445f4063a76d1 to your computer and use it in GitHub Desktop.
Save zacck-zz/e6e6fbd91233db4d6d8445f4063a76d1 to your computer and use it in GitHub Desktop.
Lambda examples in C++
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <numeric>
#include <ctime>
#include <cmath>
#include <algorithm>
std::vector<int> GenerateRandVec(int numOfNums, int min, int max);
int main() {
std::vector<int> vecVals = GenerateRandVec(10, 1, 50);
std::cout << "vector before sort" << std::endl;
for(auto val: vecVals)
std::cout << val << "\n";
// sort a vector
// pass in a reference to the beginning and end of our vector
std::sort(vecVals.begin(), vecVals.end(),
[](int x, int y){ return x < y;});
std::cout << "vector after sort" << std::endl;
for(auto val: vecVals)
std::cout << val << std::endl;
std::cout << "filter odds out" << std::endl;
std::vector<int> evenVals;
// filter one vector into another
std::copy_if(vecVals.begin(), vecVals.end(),
std::back_inserter(evenVals),
[](int x){return (x % 2 ) == 0;});
for(auto val: evenVals)
std::cout << val << std::endl;
// Sum vecor values
// Note this time we use a capture operator to enable us to use
// the `sum` value inside the lambda
std::cout << "Sum Vector Values" << std::endl;
int sum = 0;
std::for_each(vecVals.begin(), vecVals.end(),
[&](int x){ return sum += x;});
std::cout << "sum " << sum << std::endl;
// More practise using the capture list
int divisor;
std::vector<int> divVals;
std::cout << "List divosor: ";
std::cin >> divisor;
std::copy_if(vecVals.begin(), vecVals.end(),
std::back_inserter(divVals),
[&](int x) { return (x % divisor) == 0;});
for(auto val: divVals)
std::cout << val << std::endl;
return 0;
}
std::vector<int> GenerateRandVec(int numOfNums, int min, int max){
std::vector<int> vecValues;
srand(time(NULL));
int i = 0, randVal = 0;
while(i < numOfNums) {
randVal = min + std::rand() % ((max + 1) - min);
vecValues.push_back(randVal);
i++;
}
return vecValues;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment