-
October 6th, 2006, 08:09 AM
#1
Create std::set with keys of a std::map
Hi,
title says it all. Is there an easy way to create a set that contains the keys of my map? Background is, that one module of my program (a parser) needs the keys but I don't want to make the class that forms the second object of my map known to this module.
-
October 6th, 2006, 09:26 AM
#2
Re: Create std::set with keys of a std::map
You could use something like:
Code:
#include <string>
#include <map>
#include <set>
#include <algorithm>
template <class MapType>
const typename MapType::key_type& GetMapKey( typename MapType::value_type& entry )
{
return entry.first;
}
int main()
{
typedef std::map<std::string,int> TestMap;
TestMap testMap;
testMap.insert( TestMap::value_type("A",1) );
testMap.insert( TestMap::value_type("B",2) );
testMap.insert( TestMap::value_type("C",3) );
testMap.insert( TestMap::value_type("D",4) );
std::set<TestMap::key_type> testSet;
std::transform( testMap.begin(), testMap.end(), std::inserter(testSet,testSet.end()), GetMapKey<TestMap> );
return 0;
}
The std::transform() inserts each key of the map into the set, using the templated function GetMapKey() to extract the key from the map entries.
-
October 6th, 2006, 11:57 AM
#3
Re: Create std::set with keys of a std::map
one solution is pointer. you will better manage memory.
Kuphryn
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|