Why doesn't std::pair
have iterators?
std::pair
should provide iterator
and const_iterator
as well as begin()
and end()
-- just for their two members.
I think it would be useful because then we could pass them into templated functions that expect iterables, like vector
or set
.
Are there any downsides to this?
(The container adaptor classes—stack, queue and priority_queue— do not support iterators of any kind.) A table of iterator adaptors used with streams for input and output.
std::pair is a struct, the standard says the compiler determines the layout though the order must be maintained, so in the instance of std::pair<char,char> your compiler may decide to place 3-byte padding after each char for optimal alignment, so no you can't assume contiguous memory layout - end of story.
std::move does nothing on its own. The move assignment definitely invalidates iterators on both sides, though.
The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list.
One reason is that the two elements of a pair can be of different types. This doesn't fit with the iterator model.
The same goes for tuples, where having iterators would perhaps be even more appealing.
If you need an inexpensive homogenous container of a fixed length, you could use std::array<T, n>
.
The purpose of std::pair
is not to be a traditional container but rather to serve as a tuple that allows two potentially heterogeneous objects to be treated as a single one.
Additionally, because you have direct access to both parts of the pair, and because the types paired may not be the same, an iterator makes no sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With