Question:
Is it possible to overload the 'subscripting operator' [] so it will take char * as the index, similar to an array?
For example:
I want to write a class which will store 'name' and 'age'.
class_profile X
X["Mary"] = 18;
X["Mike"] = 20;
X["John"] = 12;
So it will work in such condition.
if ( X["John"] < 18 ) {
cout << "Kid !" << endl;
}
Answer:
Actually, C++ already defined such a class, std::map<>. A map is also called an associative array, which is an array whose indices aren't necessarily integers. Thus, you can use a string as the subscript of an associative array.
std::map takes a pair of elements, one is the key and the second is the associated value. In your example, the key can be a string that contains a person name, and the associated value is the person's age. std::map overloads operator [] so you can do something like this:
#include //for pair<>
#include
There are two steps here: first, you create a pair<> element using the standard class template std::pair (defined in ). The pair contains the name of the person and its associated value, namely the person's age. Then, you insert that pair into a map, and use map's subscript operator to retrieve the person's age by his or her name.