Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::deque: How do I get an iterator pointing to the element at a specified index?

I have a std::deque, and I want to insert an element at a specified index (I'm aware that std::list would be better at this). The deque::insert() function takes an iterator to specify the location to insert. Given an index, how can I get an iterator pointing to that location, so that I can pass that iterator to insert()?

For example:

void insertThing ( deque<Thing> & things, Thing thing, size_t index )
{
   deque<Thing>::iterator it = /* what do I do here? */
   things.insert ( it, thing );
}

I'm sure this is a very basic question, and I apologize for it. It's been a long time since I've used the STL, and I don't see anything in std::deque's member list that obviously does what I want. Thanks.

like image 531
Ptah- Opener of the Mouth Avatar asked Apr 09 '10 15:04

Ptah- Opener of the Mouth


People also ask

How do you get an iterator of a particular element in an vector?

Using std::next function In C++11 and above, the recommended approach is to use std::next, which advances the specified iterator by the specific number of elements. That's all about getting an iterator to a specific position in a vector in C++.

How do you access elements in deque?

Method 1: Accessing the elements by their index. The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements with square brackets. The first element can be accessed using [0] and the last element can be accessed using [-1].

Can you index into a deque?

index() searches for an element as defined by the parameter elem and returns the index at which the element is found in the python deque.

Does deque have iterators?

The iterator() method of Deque Interface returns an iterator over the elements in this deque in a proper sequence. The elements will be returned in order from first (head) to last (tail). The returned iterator is a “weakly consistent” iterator.


2 Answers

void insertThing ( deque<Thing> & things, Thing thing, size_t index )
{
   deque<Thing>::iterator it = things.begin() + index;
   things.insert ( it, thing );
}
like image 57
user184968 Avatar answered Oct 16 '22 23:10

user184968


A deque supports random access, so you should be able to say

things.insert( my_deque.begin() + index, thing);
like image 37
Stephen Avatar answered Oct 16 '22 22:10

Stephen