This code is from geeksforgeeks
list<int> list1;
list1.assign(3, 2);
list<int>::iterator it = list1.begin();
advance(it, 2);
list1.insert(it, 5);
cout << "The list after inserting"
<< " 1 element using insert() is : ";
for (list<int>::iterator i = list1.begin();
i != list1.end();
i++)
cout << *i << " ";
cout << endl;
list1.insert(it, 2, 7);
cout << "The list after inserting"
<< " multiple elements "
<< "using insert() is : ";
for (list<int>::iterator i = list1.begin();
i != list1.end();
i++)
cout << *i << " ";
cout << endl;
It shows the output like this:-
The list after inserting 1 element using insert() is : 2 2 5 2
The list after inserting multiple elements using insert() is: 2 2 5 7 7 2
So, I want to add different values in a single position than the duplication of the same value. Is that even possible? for ex- inserting 1,3,7 in 3rd position of the list.
Check the reference .
You can use one of insert()
:
template< class InputIt >
void insert( iterator pos, InputIt first, InputIt last); (until C++11)
template< class InputIt >
iterator insert( const_iterator pos, InputIt first, InputIt last ); (since C++11)
Example:
#include <iostream>
#include <vector>
#include <list>
int main(void) {
std::list<int> list1 = {2, 2, 5, 2};
std::vector<int> to_insert = {1, 3, 7};
std::cout << "before insert:";
for (int v : list1) std::cout << ' ' << v;
std::cout << '\n';
list1.insert(std::next(list1.begin(), 2), to_insert.begin(), to_insert.end());
std::cout << " after insert:";
for (int v : list1) std::cout << ' ' << v;
std::cout << '\n';
return 0;
}
Output:
before insert: 2 2 5 2
after insert: 2 2 1 3 7 5 2
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.