2

I am trying to implement a container like std::map in C++. I have a small query while overloading operator []. I see that this operator works in two ways:

  1. mymap[2] - For this case it looks for key 2 in map and return the value against this key.
  2. mymap[2]=3 - For this case it looks for key 2 in map and if key is not found than 3 is inserted in map.

I see that declaration for this operator looks like: Mapped_T &operator[](const Key_T &); but what I am not getting is that in case the key is not found I will have to insert a new element in Map but in declaration of operator[] function I don't see value being passed anywhere. So how would overloaded operator know what is value against key to be inserted?

2
  • en.cppreference.com/w/cpp/container/map/operator_at Commented Oct 12, 2016 at 23:26
  • They are both the same case. writing X = Y first evaluates X and Y before performing the assignment, and X is evaluated the same way regardless of context. Commented Oct 12, 2016 at 23:52

2 Answers 2

4

When the key does not exist, std::map constructs a new value using the value class's default constructor, and returns a reference to the newly-inserted value.

Sign up to request clarification or add additional context in comments.

5 Comments

But in this case how would actual value be inserted against that key?
As I explained to you: the actual value is constructed using the object's default constructor, and inserted. For simple types, the default constructor is zero-initialization.
Sorry, but I am still not getting it. If I call mymap[2]=3 (assume key doesn't exists for now, then 1. overloaded operator for [] is called 2. Key 2 is inserted with some default value assume it is NULL for now. But in this whole process how is 5 inserted?
The default value is 0. And where did 5 come from? There's no 5 here. Key 2 is inserted with the value of 0, operator[] then returns a reference to this value, and the = operator assigns 3 to it.
Not sure why you're getting downvoted. It's a valid answer.
3

It would be value-initialized - as if with {}, here's some pseudocode:

Mapped_T & operator[](const Key_T &k) {
    if(!has_key(k))
        insert(k, Mapped_T{});
    return at(k);
}

The important part for your question is Mapped_T{}. For aggregates it means zero-initialization, for classes with default constructor it means using that constructor.

2 Comments

So you mean intializer_list would be called to copy the actual value against the key in map?
No, there's no initializer_list anywhere in this code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.