Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I always substitute regular pointers for input iterators?

Tags:

c++

Can I always substitite pointers for InputIterators in the fashion examplified in the below code?

int a[] = {5, 6, 7, 8, 9, 10};
std::list<int> l(a, a + 4); // 5, 6, 7, 8

The constructor declaration for list is (leaving out the allocator part)

list (InputIterator first, InputIterator last);

But from the C++ reference it almost seems like anything which supports actions such as ++ (increment) and * (dereferenceing) could be used as InputIterators?

Thank you.

like image 700
jensa Avatar asked Jan 09 '23 18:01

jensa


2 Answers

C++ Standard section § 24.2.1 [iterator.requirements.general] :

Iterators are a generalization of pointers that allow a C ++ program to work with different data structures (containers) in a uniform manner.

[...]

Since iterators are an abstraction of pointers, their semantics is a generalization of most of the semantics of pointers in C ++ . This ensures that every function template that takes iterators works as well with regular pointers.

So yes, any function template that expects an iterator (as defined in the standard) is required to work when called with regular pointers.

In particular, pointers respects all the requirements of any standard C++ iterator class (including Input Iterators)

like image 197
quantdev Avatar answered Jan 26 '23 19:01

quantdev


Yes, you can. Iterator categories form a hierarchy. With each level including the level above (or below, depending on how you write it).

Forward iterators satisfy all the requirements of Input iterators, and then some. Bidirectional iterators support all the requirements of forward iterators, and then some. And finally, random access iterators, the most capable iterators of all, satisfy all the requirements of bidirectional iterators, and then some.

Pointers are random access iterators, therefore, they satisfy all the requirements of input iterators.

like image 22
Benjamin Lindley Avatar answered Jan 26 '23 17:01

Benjamin Lindley