2
votes

I want to convert a code from perl to c++, and my problem is multi key map in perl! example:

perl:

$address{name}{familyName} = $someAddress;

and keys are not unique. I want similar data structure in c++ using map or ...!? also I want to search and obtain values with first key for example I want such %keys{name} in c++ .

edited: I want to know something like if any family name for special name exists or not , also name and family name together are the key and unique not each of them.

3

3 Answers

6
votes

The equivalent to %keys{name} is done with std::map. You can use the bracket operator to access elements of the map. And it conveniently inserts a new default-constructed object if you ask for a key that isn't there yet. You might be able to duplicate the multi-key map with a map of maps, e.g., std::map<std::string, std::map<std::string, std::string> >.

If your keys might have more than one value associated with them, use std::multimap instead of map.

4
votes

You want something like:

#include <map>
#include <string>

struct Person {
   Person( const std::string & n, const std::string & f ) 
        : name( n ), family( f ) {} 

   bool operator<( const Person & p ) const {
      if ( family < p.family ) return true;
      else if ( family == p.family ) return name < p.name;
      else return false;
   }

   std::string name;
   std::string family;

};

int main() {
    std::multimap <Person, std::string> amap;
    amap.insert( 
      std::make_pair( Person( "fred", "bloggs" ), "somewhere") 
    );
    // alternate, though semantically somewhat different syntax
    amap[ Person( "fred", "bloggs" ) ] = "new address";
}    
3
votes

If the keys are not unique, you must use std::multimap, not std::map. Uniqueness of keys is exactly the difference between these two.