11

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.

  • 1
    Actually, deque is better than list at this. –  Apr 09 '10 at 15:23
  • Neil, are you sure? http://www.sgi.com/tech/stl/Deque.html says it supports "linear time insertion [...] in the middle", while http://www.sgi.com/tech/stl/List.html has "constant time insertion [...] in the middle." – Matthew Flaschen Apr 09 '10 at 15:30
  • @Matthew But you first have to find the insertion point. –  Apr 09 '10 at 15:31
  • 1
    That's actually why I decided to use deque. But by that parenthetical aside, I just meant strictly that std::list is better at inserting in the middle, not that it is better at the overall goal of finding the place in the middle to insert at and then inserting there. – Ptah- Opener of the Mouth Apr 09 '10 at 15:40

3 Answers3

22
void insertThing ( deque<Thing> & things, Thing thing, size_t index )
{
   deque<Thing>::iterator it = things.begin() + index;
   things.insert ( it, thing );
}
10

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

things.insert( my_deque.begin() + index, thing);
Stephen
  • 47,994
  • 7
  • 61
  • 70
0

I like clean soulution without warnings in code, so as std::deque::iterator operator+ overloaded for signed integer code like:

void insertThing ( deque<Thing> & things, Thing thing, size_t index )
{
   deque<Thing>::iterator it = things.begin() + index; // warning here
   things.insert ( it, thing );
}

Introduce warning. So better solution I like more:

void insertThing ( deque<Thing> & things, Thing thing, size_t index )
{
   auto it = things.begin();
   std::advance(it, index);     // clean code (warnings from system headers skipped)
   things.insert ( it, thing );
}
leanid.chaika
  • 2,143
  • 2
  • 27
  • 30