How to insert an element into a specific position of a list in C++

2 Answers

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

void printList(std::list<int> const &l) {
    for (auto const &n: l) {
        std::cout << n << " ";
    }
}

int main() {
    std::list<int> l = { 5, 2, 7, 1, 9, 3, 6, 4 };
    std::list<int>::iterator it;
    int N = 3;
    
    it = l.begin();
    for (int i = 0; i < N; i++) it++;
    

    l.insert(it, 19863);      
    
    printList(l);
    
    return 0;
}



/*
run:

5 2 7 19863 1 9 3 6 4 

*/

 



answered Apr 11, 2020 by avibootz
0 votes
#include <iostream>
#include <list>
 
void printList(std::list<int> const &l) {
    for (auto const &n: l) {
        std::cout << n << " ";
    }
}
 
int main() {
    std::list<int> l = { 5, 2, 7, 1, 9, 3, 6, 4 };
    std::list<int>::iterator it = l.begin(); 
    int N = 3;
     
    advance(it, N);

    l.insert(it, 19863);      
     
    printList(l);
     
    return 0;
}
 
 
 
/*
run:
 
5 2 7 19863 1 9 3 6 4 
 
*/

 



answered Apr 11, 2020 by avibootz

Related questions

1 answer 182 views
1 answer 189 views
1 answer 192 views
1 answer 222 views
1 answer 176 views
2 answers 259 views
...