How to insert new elements in list at a specific position in C++

1 Answer

0 votes
#include <iostream> 
#include <iterator>
#include <list>
#include <algorithm>

using std::list;
using std::cout;  
using std::endl;

int main()
{
	list<int> lst{ 1, 2, 3, 4, 5 };
	list<int>::iterator it = lst.begin();
	
	advance(it, 3);

	std::insert_iterator< std::list<int> > ins_it(lst, it);
	
	*ins_it++ = 989;
	*ins_it = 501;

	for (it = lst.begin(); it != lst.end(); it++)
		cout << *it << ' ';

	cout << endl;

	return 0;
}

/*
run:

1 2 3 989 501 4 5

*/

 



answered Apr 27, 2018 by avibootz

Related questions

1 answer 189 views
1 answer 177 views
1 answer 182 views
2 answers 254 views
1 answer 223 views
1 answer 157 views
...