Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does map have operator[] but set does not?

Tags:

c++

stl

std::map and std::set seem very similar to me (but in their use and in their description), so I do not understand why std::set does not implement its version of operator[]. I suspect it is linked to the fact that elements in a std::set are const, but even then why not implement an operator[] that either returns a const reference or creates a new element ?

Depending on the answer to this first question, would it be possible/a good idea to create a version a std::set that implements operator[] ?

like image 485
Jeremy Maille Avatar asked Dec 02 '22 09:12

Jeremy Maille


2 Answers

Well, std::map<Key, Val> maps Key to Val.

That is, m[key] yields a reference to the val. You have the key, and want to find the associated value (or associate a value with that key).

In a std::set<Elem>, the element would be its own key. So, the only thing you could get back would be the thing you already have. What would you use this operation for?

A set is not for mapping one thing to another - that's what a map does. A set is for recording whether or not an element belongs to some collection. So, the only sane thing to use it for is checking, given some element, whether or not that element is a member of the set. We do this with s.find(elem) != s.end() or, from c++20, s.contains(elem).

The fact that the set is described as std::set<Key, ...> may be a source of confusion - I suspect this is just because it's used for searching in the same way as the map key.

You could in principle choose to characterize a set as map<Elem, bool>, but unless you want to really store the bool (which would be wasteful), the element access and iterator semantics would be a bit hairy. That is, it would be mathematically accurate and consistent, but either wasteful or complicated in implementation.

like image 143
Useless Avatar answered Dec 04 '22 03:12

Useless


In fact a map is an associated array only instead of integer indices it uses keys as indices.

As ordinary arrays have the subscript operator then and maps have a similar subscript operator.

On the other hand, sets are not associated arrays. In sets keys are their data. So a question arises what should an expression like this set[key] return? There is no greate sense to return itself and moreover when the returned value may not be changed.

like image 27
Vlad from Moscow Avatar answered Dec 04 '22 01:12

Vlad from Moscow