Overload Operator []


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;}


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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

Top 5 B2B SaaS Marketing Agencies for 2023

In recent years, the software-as-a-service (SaaS) sector has experienced exponential growth as more and more companies choose cloud-based solutions. Any SaaS company hoping to stay ahead of the curve in this quickly changing industry needs to invest in effective marketing. So selecting the best marketing agency can mean the difference

technology leadership

Why the World Needs More Technology Leadership

As a fact, technology has touched every single aspect of our lives. And there are some technology giants in today’s world which have been frequently opined to have a strong influence on recent overall technological influence. Moreover, those tech giants have popular technology leaders leading the companies toward achieving greatness.

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.