Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::pair have iterators?

Tags:

c++

stl

std-pair

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?

like image 247
Frank Avatar asked Dec 06 '12 17:12

Frank


People also ask

Which of the following containers does not support iterators?

(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.

Is std :: pair contiguous?

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.

Does std :: move invalidate iterators?

std::move does nothing on its own. The move assignment definitely invalidates iterators on both sides, though.

Why do iterators exist?

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.


2 Answers

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>.

like image 123
NPE Avatar answered Sep 20 '22 04:09

NPE


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.

like image 30
Omaha Avatar answered Sep 22 '22 04:09

Omaha