#include <iostream>
#include <map>
int main(void) {
std::map<char, int> mapint;
mapint.insert({'a', 1});
mapint.insert({'b', 2});
// subscript operator is overloaded to return iterator.second (the value with key 'a')
int ex = mapint['a'];
std::cout << ex << std::endl;
// Why does this NOT traslate to 1=10 ?
// instead it replaces or creates pair <'a',10>...
mapint['a'] = 10;
for (auto i : mapint) {
std::cout << i.first << "," << i.second << std::endl;
}
// OUTPUT
// 1
// a,10
// b,2
return 0;
}
How is the map
operator being overloaded? I tried looking at the code for map but i couldn't find anything to answer my question...
I want to make something similar for one of my classes and i think figuring this out should help alot!
CodePudding user response:
It basically just builds on top of existing methods found within map. It is implemented along the lines of...
template<typename Key, typename Value>
struct map {
// This operator cannot be declared 'const', since if the key
// is not found, a new items is automatically added.
Value& operator [] (const Key& key) {
// attempt to find the key
auto iter = find(key);
// if not found...
if(iter == end()) {
// insert new item (with a default value to start with)
iter = insert(std::make_pair(key, Value()));
}
// return reference to the data item stored for 'key'
return iter->second;
}
};
CodePudding user response:
To overload the [] operator you can do as follows (in pseudo-code):
struct A
{
your_return_type operator[](your_argument_list)
{
your implementation
}
};
If you want to return a reference to some class member, then you may have to implement 2 versions of this operator, one const
, which returns a non-modifiable reference, and one non-const
, which returns a modifiable refence.
struct A
{
your_modifiable_return_type_ref& operator[](your_argument_list)
{
your implementation
}
const your_non_modifiable_return_type_ref& operator[](your_argument_list) const
{
your implementation
}
};