Thursday, March 26, 2009

c++ stl - use transform to copy keys from map to set

//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <iostream>
#include <map>
#include <set>
#include <iterator>

typedef std::map<std::string, int> MyMap;

// also known as select1st in SGI STL implementation
template<typename T_PAIR>
struct GetKey: public std::unary_function<T_PAIR, typename T_PAIR::first_type>
{
   const typename T_PAIR::first_type& operator()(const T_PAIR& item) const
   {
      return item.first;
   }
};

int main(int argc, char** argv)
{
   MyMap m1,m2;

   m1["a"] = 1;
   m1["b"] = 2;
   m2["c"] = 3;
   m2["b"] = 3;

   std::set<std::string> s;
   std::transform(m1.begin(), m1.end(), std::inserter(s, s.begin()), GetKey<MyMap::value_type>());
   std::transform(m2.begin(), m2.end(), std::inserter(s, s.begin()), GetKey<MyMap::value_type>());
   std::copy(s.begin(), s.end(), std::ostream_iterator<std::string>(std::cout, " "));
   std::cout << std::endl;
   return 0;
}