也许以下可能有用:
#include <iostream>#include <iterator>#include <algorithm>#include <map>#include <set>#include <string>template< class Key,class T,class Comparator, class MapAllocator, class SetAllocator>void make_key_set(const std::map<Key,T,Comparator,MapAllocator>& map, std::set<Key,Comparator,SetAllocator>& set){ set.clear(); typedef typename std::map<Key,T,Comparator,MapAllocator> map_type; typename map_type::const_iterator itr = map.begin(); while (map.end() != itr) { set.insert((itr++)->first); }}int main(){ std::map<std::string, double> m; m["one"] = 1.1; m["two"] = 2.2; m["three"] = 3.3; std::set<std::string> key_set; make_key_set(m,key_set); std::copy(key_set.begin(), key_set.end(), std::ostream_iterator<std::string>(std::cout, "n")); return 0;}使用STL兼容序列(例如std :: vector,std :: deque或std :: list)的 make_key_set
函数的重载可以如下所示:
template< class Key,class T,class Comparator, class MapAllocator, class SeqAllocator, template<class,class> class Sequence>void make_key_set(const std::map<Key,T,Comparator,MapAllocator>& map, Sequence<Key,SeqAllocator>& sequence){ sequence.clear(); typedef typename std::map<Key,T,Comparator,MapAllocator> map_type; typename map_type::const_iterator itr = map.begin(); while (map.end() != itr) { sequence.push_back((itr++)->first); }}


