Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::array::begin not return an iterator?

I am trying to build a nested iterator template and relied on iterators having various traits like value_type. But as it turns out, not all STL types even return iterators with those traits. For instance:

#include <array>
#include <type_traits>

template <typename T>
using iterator_t = decltype(std::declval<T>().begin());

static_assert(std::is_same_v<iterator_t<std::array<int, 3>>, int*>);

This code compiles and shows that the actual type of the array iterator is int*. In that case, how can I still access traits such as value_type etc?

like image 791
Jan Schultke Avatar asked May 26 '20 10:05

Jan Schultke


People also ask

Do arrays have iterators?

The most common iterator in JavaScript is the Array iterator, which returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary.

What is Arr begin () in C++?

C++ Array Library - begin() Function The C++ function std::array::begin() returns an iterator which points to the start of the array.

Can I use begin () for an array in C++?

begin() function is used to return an iterator pointing to the first element of the array container. begin() function returns a bidirectional iterator to the first element of the container. Syntax : arrayname.

Can you use iterator on array C++?

Iterating through an array C++ is the concept which involves going through each element one by one. There are a variety of methods to iterate through an array in C++; here are a few examples. In C++, you can iterate through arrays by using loops in the statements.


2 Answers

The standard doesn't specify how the iterator should be implemented and what the exact type it should be. In fact pointers like int* does satisfy the requirements of the iterator of std::array, so it's quite legitimate for implementation.

You can use std::iterator_traits to get the value_type as std::iterator_traits<iterator_t<std::array<int, 3>>>::value_type, it works with pointers too.

like image 166
songyuanyao Avatar answered Oct 02 '22 21:10

songyuanyao


int* is an iterator as it satisfies all the requirements necessary of an iterator.

Informally:

  1. You can deference it (unless it's past the final element of the array).

  2. You can increment it (as it's a pointer in an array).

  3. You can copy int* to another int*.

  4. You can call std::swap with int* as the types.

like image 37
Bathsheba Avatar answered Oct 02 '22 20:10

Bathsheba