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.
void insertThing ( deque<Thing> & things, Thing thing, size_t index )
{
deque<Thing>::iterator it = things.begin() + index;
things.insert ( it, thing );
}
deque支持随机访问,所以你应该可以说
things.insert( my_deque.begin() + index, thing);
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 );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.