Skip to content

Instantly share code, notes, and snippets.

@ADCDS
Created April 26, 2017 17:19
Show Gist options
  • Save ADCDS/93ea33b5cece37e817f01465e2a53968 to your computer and use it in GitHub Desktop.
Save ADCDS/93ea33b5cece37e817f01465e2a53968 to your computer and use it in GitHub Desktop.
Generic Map to String Map (convert_to_string_map) c++
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <functional>
#include <string>
#include <iostream>
template <typename T1, typename T2>
static std::map<std::string, std::string> convert_to_string_map(std::map<T1, T2> _map_in,
std::function<std::pair<std::string, std::string>(T1, T2) > converter) {
std::map<std::string, std::string> retval;
for (auto _map_it : _map_in) {
auto _values = converter(_map_it.first, _map_it.second);
retval[_values.first] = _values.second;
}
return retval;
}
std::pair<std::string, std::string> testFunct(char a, int b) {
std::pair<std::string, std::string> retval;
retval.first = std::to_string(a);
retval.second = std::to_string(b);
return retval;
}
int main() {
std::map<char, int> first;
first['a'] = 10;
first['b'] = 30;
first['c'] = 50;
first['d'] = 70;
std::map<std::string, std::string> newMap;
std::function < std::pair<std::string, std::string>(char, int) > myFunc = testFunct;
newMap = convert_to_string_map(first, myFunc);
std::cout << "Old Map:\n";
for (auto _map_it : first) {
printf("%c -> %d\n", _map_it.first, _map_it.second);
}
std::cout << "\nNew map:\n";
for (auto _map_it : newMap) {
printf("%s -> %s\n", _map_it.first.c_str(), _map_it.second.c_str());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment