Created
August 9, 2011 02:51
-
-
Save johnbellone/1133305 to your computer and use it in GitHub Desktop.
Flatten an std::map into an std::vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ -O3 -I/opt/local/include -L/opt/local/lib -lboost_system flatten.cc | |
#include <iostream> | |
#include <algorithm> | |
#include <map> | |
#include <vector> | |
#include <string> | |
#include <boost/bind.hpp> | |
#include <boost/bind/placeholders.hpp> | |
namespace { | |
/*static*/ void print(const std::string& elem) | |
{ | |
std::cout << elem << std::endl; | |
} | |
} | |
template <typename K, typename V> | |
std::size_t flatten(std::map<K,V>& m, std::vector<V>& v) | |
{ | |
v.clear(); | |
v.reserve(m.size()); | |
std::transform(m.begin(), m.end(), | |
std::back_inserter(v), | |
boost::bind(&std::map<K,V>::value_type::second, _1)); | |
return v.size(); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
std::map<int, std::string> m; | |
std::vector<std::string> v; | |
m[1] = "World"; | |
m[0] = "Hello"; | |
m[2] = "!!"; | |
flatten(m,v); | |
std::for_each(v.begin(), v.end(), print); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment