Skip to content

Instantly share code, notes, and snippets.

@scolton99
Created February 16, 2021 15:41
Show Gist options
  • Save scolton99/5a60b504d7b0fb45aa80bc1549a47675 to your computer and use it in GitHub Desktop.
Save scolton99/5a60b504d7b0fb45aa80bc1549a47675 to your computer and use it in GitHub Desktop.
C++ Vector Map
#include <functional>
#include <iterator>
#include <vector>
#include <iostream>
namespace std {
template<typename S, typename E>
vector<E> vector_map(typename std::vector<S>::iterator start, typename std::vector<S>::iterator end, std::function<E(S)> lambda) {
vector<E> ret;
do {
ret.push_back(lambda(*start));
++start;
} while (start != end);
return ret;
}
}
@scolton99
Copy link
Author

#include <iostream>
#include "vector_map.h"

int main() {
  std::vector<std::string> str_vec = { "0101", "-6", "12589" };

  auto int_vec = std::vector_map<std::string, int>(str_vec.begin(), str_vec.end(), [](const std::string s) {
    return std::stoi(s);
  });

  for (int i : int_vec) {
    std::cout << std::to_string(i) <<std::endl;
  }
}

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