Last active
March 11, 2017 00:33
-
-
Save loloof64/75240107d3ca9fb14b49ba21fb3feb0d to your computer and use it in GitHub Desktop.
Example of c++11/14 numeric vector transform into squares
This file contains hidden or 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
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <functional> | |
template <typename T> | |
void traceVectorValues(const std::vector<T> &); | |
template <typename T> | |
void transformVectorWithUnaryFunction(std::vector<T> &, std::function<T(T)>); | |
int main(){ | |
using namespace std; | |
typedef double InputType; // If we need to change inputs type, we just have to do it here. | |
vector<InputType> values{1,2,3,4,5,6,7,8,9.6}; | |
auto squareFunc = [](auto input){return input * input;}; | |
traceVectorValues(values); | |
transformVectorWithUnaryFunction<InputType>(values, squareFunc); | |
traceVectorValues(values); | |
return 0; | |
} | |
template <typename T> | |
void traceVectorValues(const std::vector<T> &vec) { | |
using namespace std; | |
cout << "["; | |
for (auto current : vec){ | |
cout << current << ", "; | |
} | |
cout << "\b\b]" << endl; | |
} | |
template <typename T> | |
void transformVectorWithUnaryFunction(std::vector<T> &vec, std::function<T(T)> func) { | |
using namespace std; | |
transform(vec.begin(), vec.end(), vec.begin(), func); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think that one big improvement would be to restrict transformVectorWithUnaryFunction() template parameter to numeric value. However, I don't know how I can do that.