Skip to content

Instantly share code, notes, and snippets.

@wdanxna
Created November 20, 2018 03:57
Show Gist options
  • Save wdanxna/becbdd30046e8adbc1d20e1d4ad0fc5e to your computer and use it in GitHub Desktop.
Save wdanxna/becbdd30046e8adbc1d20e1d4ad0fc5e to your computer and use it in GitHub Desktop.
map and zip function in c++
// Example program
#include <iostream>
#include <string>
#include <vector>
using std::vector;
template<typename P, typename Iterator, typename Mapper>
void map(Iterator current, Iterator end, Mapper mapper, vector<P>& ret) {
if (current == end) return;
ret.push_back(mapper(*current));
map(++current, end, mapper, ret);
};
template<typename IteratorA, typename IteratorB, typename Zipper, typename P>
void zip(IteratorA a, IteratorA aEnd, IteratorB b, IteratorB bEnd, Zipper zipper, vector<P>& ret) {
if (a == aEnd || b == bEnd) return;
ret.push_back(zipper(*a, *b));
zip(++a, aEnd, ++b, bEnd, zipper, ret);
}
int main()
{
vector<int> a{1,2,3,4,5};
vector<int> ret;
map(a.begin(), a.end(), [](int i){return i*i;}, ret);
vector<float> ret2;
zip(a.begin(), a.end(), ret.begin(), ret.end(), [](int a, int b){ return (float)a + (float)b;}, ret2);
for (auto& i : ret2) {
std::cout << i << ",";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment