C++ Logo


Advanced search

Re: Requiring operator[] for random-access and bidirectional containers?

From: Phil Ratzloff <Phil.Ratzloff_at_[hidden]>
Date: Mon, 31 Oct 2022 13:44:15 +0000
That makes sense, and I agree.

I also need the find_or_create() behavior in map, not just find for my purposes. If using a vector or deque, for instance, I should have a pre-extended container. In the case of map, which would have sparse keys, I wouldn't be pre-extending it.

From: Oleksandr Koval <oleksandr.koval.dev_at_[hidden]>
Sent: Monday, October 31, 2022 7:03 AM
To: sg19_at_[hidden]
Cc: Phil Ratzloff <Phil.Ratzloff_at_[hidden]>
Subject: Re: [SG19] Requiring operator[] for random-access and bidirectional containers?

You don't often get email from oleksandr.koval.dev_at_[hidden]<mailto:oleksandr.koval.dev_at_[hidden]>. Learn why this is important<https://aka.ms/LearnAboutSenderIdentification>

First of all, we don't have concepts for containers, only for ranges and iterators. For containers we have only named requirements. If you are asking why `operator[]` is not part of `random_access/bidirectional_range` then the answer is simple: because they are just ranges with `random_access/bidirectional_iterator`, nothing more, nothing less. Having `operator[]` for them doesn't make much sense. For map and vector `operator[]` behaves differently, for map it doesn't even exist for const `*this` which makes it pretty useless for any algorithm which is not supposed to modify the input sequence.
I guess that you need some generic `find_by(const Container&, T)` where T could be `size_type` for key-less sequences or `key_type` for ones with key. The first part obviously doesn't need any new concepts, any range can satisfy it, the second part can be named like `findable/searchable_range` and require member `find(key_type)`.

On Sun, Oct 30, 2022 at 6:57 PM Phil Ratzloff via SG19 <sg19_at_[hidden]<mailto:sg19_at_[hidden]>> wrote:
operator[] makes coding much simpler and clearer when accessing elements in random_acess_ranges like vector and deque. It is also useful for the bidirectional_ranges like map and unordered_map. We could like to use operator[] in the graph algorithms and doing so would support writing more generic code, but the concepts for those ranges don't require operator[].

Is there a reason operator[] isn't a requirement for random_access_range? For bidirectional_range?

We would create a concept that would require operator[]. What caveats are there in doing that?

SG19 mailing list
Oleksandr Koval.

Received on 2022-10-31 13:44:18