Created
October 23, 2020 04:09
-
-
Save lamarmarshall/d6b7f4f28ffdc450d94dc2d3fd7bb5ee to your computer and use it in GitHub Desktop.
C++, lambda, map, filter, reduce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.cpp | |
// tutorial | |
// | |
// Created by king lamar on 10/22/20. | |
// | |
#include <iostream> | |
#include <vector> | |
#include <random> | |
#include <ctime> | |
using namespace std; | |
std::vector<int> GenerateRandomVect(int numberOfnums, int min, int max); | |
int main(int argc, const char * argv[]) { | |
// sort | |
vector<int> vecVals = GenerateRandomVect(10, 1, 1000); | |
sort(vecVals.begin(), vecVals.end(), [](int x, int y){ return x < y ;}); | |
for( auto v: vecVals){ | |
cout << v << " " ; | |
} | |
cout << endl; | |
// filter | |
vector<int> even; | |
copy_if(vecVals.begin(), vecVals.end(), | |
back_inserter(even), | |
[](int x){return (x % 2 ) == 0;}); | |
for( auto v: even){ | |
cout << v << " " ; | |
} | |
cout << endl; | |
//map | |
int sum = 0; | |
for_each(vecVals.begin(), vecVals.end(), | |
[&](int x){ sum += x;}); | |
cout << "Sum is " << sum << endl; | |
return 0; | |
} | |
std::vector<int> GenerateRandomVect(int numberOfnums, int min, int max){ | |
std::vector<int> vecValues; | |
srand(time(NULL)); | |
int i = 0, randVal = 0; | |
while( i < numberOfnums){ | |
randVal = min + 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