How to remove a range elements from a list in C++

1 Answer

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

void printList(std::list<int> const &l) {
    for (auto const &n: l) {
        std::cout << n << " ";
    }
}
void eraseRange(std::list<int> &l, int a, int b) {
    std::list<int>::iterator ita = l.begin(); 
    std::list<int>::iterator itb = l.begin(); 

    advance(ita, a); 
    advance(itb, b + 1); 
 
    l.erase(ita, itb);
}

int main() {
    std::list<int> l = { 5, 2, 7, 1, 9, 3, 6, 4 };
    int a = 3, b = 6;
 
    eraseRange(l, a, b);
    
    printList(l);
    
    return 0;
}



/*
run:

5 2 7 4 

*/

 



answered Apr 11, 2020 by avibootz

Related questions

1 answer 187 views
2 answers 185 views
1 answer 169 views
1 answer 139 views
...