0

Say I have an std::map type which for example is defined as follows.

std::map<int, int>* someMap;

If I weren't using a pointer, I could simply add an element using the index operator. However in this case, since I have a pointer, would the following be the correct way to insert using the index operator.

(*someMap)[someIndex] = someValue;
0

3 Answers 3

3

Yes. The operator [] is overloaded for the Map class. It has to be used directly with the object.

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

Comments

1

Make sure you point someMap at something. Otherwise, its just contains a meaningless address derived from garbage on the stack. Here's an example allocating from the heap:

  std::map<int, int>* someMap = new std::map<int, int>();

and once thats done, yes, you are correct in how to use it:

  (*someMap)[someIndex] = someValue;

and be sure to cleanup after yourself

  delete someMap;

Comments

0

Yes, your code is fine:

(*someMap)[someIndex] = someValue;

1 Comment

Why shouldn't I call like somemap->[someIndex] = someValue? Why it should be directly called with object restricting the pointer?

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.