0

I don't know what I did wrong but I have a map:

std::map<std::pair<ID, ID>, std::queue<Datum>> readQueues;

Everything's fine until I call readQueues[std::make_pair(src, dst)]; and then I get an error that my arguments do not match the arguments of the function. The funny thing is that the whole thing works with std::map::find and map::at with the exact same arguments... Any ideas?

1
  • 7
    What's the type of src and dst? Commented Nov 26, 2014 at 19:46

2 Answers 2

5

The subscript-operator of map cannot work for const maps (or const references to maps for that matter). That is because it may actually change the map - recall that

m[a] = 7;

will work even if a is not present in m. In that case a is inserted in to m first. Thus the semantic involves a potential modification, and that is exactly what const member functions shall not do.

You can instead use find which will return an iterator. In particular, find returns end() when the passed key is not contained yet.

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

Comments

2

The operator[] is non-const, so you cannot use it when you only have a const-reference to your map, unlike find and at.

2 Comments

@lightxbulb: The map itself mustn't be const. The []-operator inserts new elements into the map.
Sorry I deleted the comment, because Columbo actually answered the question faster than I could type.

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.