|
|||||||||||||
|
Section 34:
|
[34.2] How can I make a perl-like associative array in C++?
Use the standard class template std::map<Key,Val>:
#include <string>
#include <map>
#include <iostream>
int main()
{
// age is a map from string to int
std::map<std::string, int, std::less<std::string> > age;
age["Fred"] = 42; // Fred is 42 years old
age["Barney"] = 37; // Barney is 37
if (todayIsFredsBirthday()) // On Fred's birthday...
++ age["Fred"]; // ...increment Fred's age
std::cout << "Fred is " << age["Fred"] << " years old\n";
...
}
Nit: the order of elements in a std::map<Key,Val> are in the sort
order based on the key, so from a strict standpoint, that is different from
Perl's associative arrays which are unordered.
|
||||||||||||