Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert element after the iterator position

Tags:

c++

stl

std::list.insert inserts an element before the iterator position. How can I insert an element after an iterator position.

like image 835
Noman Ali Avatar asked May 16 '12 10:05

Noman Ali


People also ask

How do you add an element to a list in C++?

Using insert(pos_iter,ele_num,ele) : insert() is used to insert the elements at any position of list. . This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1.

How do you add elements to a vector?

To add elements to vector, you can use push_back() function. push_back() function adds the element at the end of this vector. Thus, it increases the size of vector by one.

How do you append to a vector in C++?

Appending to a vector means adding one or more elements at the back of the vector. The C++ vector has member functions. The member functions that can be used for appending are: push_back(), insert() and emplace(). The official function to be used to append is push_back().

Can we push front in vector?

Adding to the front of a vector means moving all the other elements back. If you want (to constantly perform) front insertion, you might really want to use list or deque . The only way to know how to speed up your program is with profiling. You should just program first then profile it and find out.


1 Answers

that's what list::insert does. Just increment your iterator before inserting your value:

if (someIterator != someList.end()) {
    someIterator++;
}
someList.insert(someIterator, someValue);
like image 182
Botz3000 Avatar answered Sep 20 '22 18:09

Botz3000