CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    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.

  2. #2
    Join Date
    Jan 2001
    Posts
    253

    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.

  3. #3
    Join Date
    Feb 2002
    Posts
    5,757

    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
  •  





Click Here to Expand Forum to Full Width

Featured