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 XX["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