Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use std::max_element() on std::deque in c++11?

Tags:

c++

std

c++11

deque

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!

like image 756
user5025141 Avatar asked May 17 '17 19:05

user5025141


People also ask

What is STD Deque?

std::deque (double-ended queue) is an indexed sequence container that allows fast insertion and deletion at both its beginning and its end. In addition, insertion and deletion at either end of a deque never invalidates pointers or references to the rest of the elements.

What is Deque C++?

In C++, the STL deque is a sequential container that provides the functionality of a double-ended queue data structure. In a regular queue, elements are added from the rear and removed from the front. However, in a deque, we can insert and remove elements from both the front and rear. Deque Data Structure.


Video Answer


2 Answers

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.

like image 155
NathanOliver Avatar answered Sep 21 '22 07:09

NathanOliver


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.

like image 35
Cory Kramer Avatar answered Sep 23 '22 07:09

Cory Kramer