开发者

convert perl map with multiple key to c++

开发者 https://www.devze.com 2022-12-23 03:05 出处:网络
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;

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 开发者_StackOverflowkeys 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.


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.


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";
}    


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号