Skip to content

Instantly share code, notes, and snippets.

@bluurn
Created March 1, 2019 14:05
Show Gist options
  • Save bluurn/d60d9375a281f6f2ac422c6fe27eab82 to your computer and use it in GitHub Desktop.
Save bluurn/d60d9375a281f6f2ac422c6fe27eab82 to your computer and use it in GitHub Desktop.
CPP: Implementation of Sqr via templates
#include <iostream>
#include <map>
#include <utility>
#include <vector>
using namespace std;
template <typename T>
T Sqr(T x) {
return x * x;
}
template <typename First, typename Second>
pair<First, Second> Sqr(const pair<First, Second>& p) {
return {Sqr(p.first), Sqr(p.second)};
}
template <typename T>
vector<T> Sqr(const vector<T>& v) {
vector<T> result = {};
for (const auto& it : v) {
result.push_back(Sqr(it));
}
return result;
}
template <typename K, typename V>
map<K, V> Sqr(const map<K, V>& m) {
map<K, V> result = {};
for (const auto& it : m) {
result[it.first] = Sqr(it.second);
}
return result;
}
int main() {
vector<int> v = {1, 2, 3};
cout << "vector:";
for (int x : Sqr(v)) {
cout << ' ' << x;
}
cout << endl;
map<int, pair<int, int>> map_of_pairs = {{4, {2, 2}}, {7, {4, 3}}};
cout << "map of pairs:" << endl;
for (const auto& x : Sqr(map_of_pairs)) {
cout << x.first << ' ' << x.second.first << ' ' << x.second.second << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment