tags:

views:

190

answers:

3

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.

+6  A: 

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.

Kristo
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.
Yadollah
@YY, then you probably want something along the lines of Neil's answer, since the full name is unique. To find out if a certain family or given name exists, you can simply walk the map from `begin()` to `end()` and compare that name with the appropriate part of the `Person` struct.
Kristo
+3  A: 

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

John Zwinck
tnx for your helping. I found an easy solution to solve my problem. It is having two map: one multimap for mapping a name with some familyName.and one map for map name and family with one address. It is very fast to response my queries!
Yadollah
+4  A: 

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";
}    
anon
`operator<` is required for the structure. Isn't it?
Naveen
@Naveen, you need `operator<` defined for your key or some comparison functor that becomes part of the map's type.
Kristo
+1 for compressing first and last names into a single key object.
Kristo