Is there a way to check if a sequence container is contiguous in memory? Something like:
#include
#include
#include
No, there is not compiletime trait for this.
The draft C++1z Standard defines contiguity as a runtime property of an iterator range. Note there is no compiletime std::contiguous_iterator_tag
corresponding to this iterator category.
24.2 Iterator requirements [iterator.requirements]
24.2.1 In general [iterator.requirements.general]
5 Iterators that further satisfy the requirement that, for integral values
n
and dereferenceable iterator valuesa
and(a + n), *(a + n)
is equivalent to*(addressof(*a) + n)
, are called contiguous iterators. [ Note: For example, the type “pointer to int” is a contiguous iterator, butreverse_iterator
is not. For a valid iterator range[a,b)
with dereferenceablea
, the corresponding range denoted by pointers is[addressof(*a),addressof(*a) + (b - a));
b
might not be dereferenceable. — end note ]
One way to test for this at runtime would be
#include
#include
#include
#include
#include
#include
Live Example. This prints false
for the list
, map
and unordered_multimap
, and true
for the C-array, and the std::array
, string
and vector
. It prints true
for small subranges within a deque
and false
for large subranges. It also prints false
for an iterator range consisting of reverse iterators.
UPDATE: as commented by @T.C. the original N3884 proposal did have a
struct contiguous_iterator_tag : random_access_iterator_tag {};
so that tag-dispatching on iterator categories would not break. However, this would have broken non-idiomatic code with class template specializations on random_access_iterator_tag
. The current draft hence does not contain a new iterator category tag.