convert perl map with multiple key to c++
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.
精彩评论