0

What does [] operator means for map

Hi As we all know that subscript operator [] helps to identify the element into sequential container... However , we can use this [] for map insert functionality as below: mymap[key] = value; I am trying to find out how we can implement the same functionality in custom user defined map.. Any hint would be useful... I tried to use operator [] and can also get "key" from function argument but how to take "value" into function? Current source code is as below : https://code.sololearn.com/cJWK6P984Ab5/?ref=app Feel free to provide any improvement on the source code.. one known point is yet open that everything is public in data due to struct and later on will strict it with access specifier..

16th Jul 2020, 5:47 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 ответов
+ 1
1.using type aliases First add these 2 typedefs to struct node typedef U value_type; typedef value_type& reference; The [] will then be typename node<T,U>::reference operator[](const T& key) { //return value if key is found //else add the key and default //value to the map auto res=(this->search(key)); if(res) return res->value; else return (this->insert(key,U{}))->value; } 2.using trailing return type syntax auto operator[](const T& key) ->decltype(node{key,declval<U>()}.value)& { //return value if key is found //else add the key and default //value to the map auto res=(this->search(key)); if(res) return res->value; else return (this->insert(key,U{}))->value; }
16th Jul 2020, 9:25 PM
Anthony Maina
Anthony Maina - avatar
+ 1
17th Jul 2020, 10:54 AM
Ketan Lalcheta
Ketan Lalcheta - avatar