7

Can I code like std::max_element(std::begin(my_deque), std::end(my_deque))?

I am asking because I know deque is not guaranteed to store continuously, so I want to know if it will behave correctly when using functions involving iterator like std::max_element?

Thank you very much!

user5025141
  • 399
  • 1
  • 3
  • 15
  • Are you worried that it won't be guaranteed to always work? – juanchopanza May 17 '17 at 19:41
  • 1
    they spec only requires `class ForwardIt` so this should work for any collection that implements forward iteration. It has nothing to do with contiguous storage at all. – Brad Allred May 17 '17 at 19:42
  • 1
    `std::max_elements` only requires a forward iterator see: http://en.cppreference.com/w/cpp/algorithm/max_element – Richard Critten May 17 '17 at 19:42
  • 1
    `max_element` only requires that the iterator is a ForwardIterator. It does not require random access/data continuitiy – kmdreko May 17 '17 at 19:43
  • 11
    The whole point of using iterators rather than pointers is to make this kind of stuff work. – T.C. May 17 '17 at 19:44
  • 1
    There's actually a second point to iterators: to not compile code which can't work. `std::sort` will fail to compile, if you pass Forward Iterators. – MSalters May 18 '17 at 06:10
  • Achtung grammar Nazi… if you give me a gold bar every day, and I put it on a heap in my basement, I'm storing them continuously. If you give me 100 gold bars, and I put them all in a row, I am storing them contiguously. Either way you may assume I will be very grateful for all the gold. ;-) – Arne Vogel May 19 '17 at 11:49

2 Answers2

7

std::max_element has a signature in the form of

template<class ForwardIterator>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last);

From the template type name we know that it requires a forward iterator. Per [container.requirements.general]-Table 96 we know that std::deque uses

any iterator category that meets the forward iterator requirements

So since it uses a forward iterator or better it will always be okay.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
6

Yes it will work correctly. The overload of std::max_element that will be invoked in this case is

template< class ForwardIt > 
ForwardIt max_element(ForwardIt first, ForwardIt last);

The only requirements on the iterators are

first, last - forward iterators defining the range to examine

So there is no requirement about random access iterators, only forward iterators.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • You're right about ``max_element`` requiring forward iterators only, however there seems to be some confusion about the category of ``std::deque`` iterators (they're random access). Having random access iterators does not imply contiguous storage. – Arne Vogel May 19 '17 at 11:44