C++ Logo

std-discussion

Advanced search

Re: Indexes in ranged loops for all containers

From: Joey Pendergrast <joey.pendergrast_at_[hidden]>
Date: Wed, 4 May 2022 16:51:38 -0400
Great, thanks to both of you!

On Wed, May 4, 2022, 4:39 PM Kilian Henneberger via Std-Discussion <
std-discussion_at_[hidden]> wrote:

>
> Am 04.05.2022 um 21:56 schrieb Jens Maurer via Std-Discussion:
>
> On 04/05/2022 21.43, Joey Pendergrast via Std-Discussion wrote:
>
> I like the way that std::map gives the key and value for ranged loops:
> for (auto& [key, value] : my_map)
>
> Why don't other containers allow for the "index" to also be gotten in a similar way?
>
> for (auto& [index, value] : any_container) would be convenient to have as well.
>
> Or, can this be done, but I'm just unaware? Thanks in advance.
>
>
> Maybe something like
>
> for (auto& [value, index] : std::views::zip_view(my_vector, std::views::iota_view(0, my_vector.size()))) { ...}
>
> could work.
>
> Jens
>
>
> The correct syntax in C++23 will be:
>
> for (auto [value, index] : std::views::zip(my_vector, std::views::iota(0))
> { ... }
>
> You have to use "auto [value, index]" or "auto&& [value, index]" as
> dereferencing a zip_view::iterator returns a std::pair (or std::tuple) by
> value.
> Additionally, P2164R5 <https://wg21.link/p2164r5> proposes
> std::views::enumerate for C++26.
> In P2214R0
> <https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2214r0.html#enumerates-first-range>
> is explained, why enumerate differs from zip + iota.
>
> Best regards,
> Kilian
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>

Received on 2022-05-04 20:51:50