Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Dec 16, 1999

Overload Operator []

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 
#include 
#include 
using namespace std;
int main()
{
pair Person(string"Lee"),23); /*create a pair */

map mp; /*create a map*/

mp.insert(Person); /*insert pair into map*/

int age = mp["john"]; /*age = 23; string used as subscript */

return 0;
}

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.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap