Skip to content

Instantly share code, notes, and snippets.

@loloof64
Last active March 11, 2017 00:33
Show Gist options
  • Save loloof64/75240107d3ca9fb14b49ba21fb3feb0d to your computer and use it in GitHub Desktop.
Save loloof64/75240107d3ca9fb14b49ba21fb3feb0d to your computer and use it in GitHub Desktop.
Example of c++11/14 numeric vector transform into squares
#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);
}
@loloof64
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment