Search code examples
c++loopswhile-loopnested-loopsstdlist

How to use the member type iterator of std::list with a while loop to make simple changes to a list


I create and modify a simple list. I replace the element at index 1 of the list. How would I semantically accomplish the same thing with a while loop. The tutorial instructor remarked that the current code is quite ugly and a while loop would accomplish the same thing in a much more simple and pretty fashion. I can't figure it out.

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers;

    numbers.push_back(1);
    numbers.push_back(2);
    numbers.push_back(3);
    numbers.push_front(0);

    std::list<int>::iterator it = numbers.begin();
    it++;
    numbers.insert(it, 100);
    std::cout << "Current element is: " << *it << '\n';

    std::list<int>::iterator eraseIt = numbers.begin();
    eraseIt++;
    eraseIt = numbers.erase(eraseIt);
    std::cout << "erasing at element: " << *eraseIt << '\n';

    for (std::list<int>::iterator it = numbers.begin(); it != numbers.end();) {
        if (*it == 2) {
            numbers.insert(it, 1234);
        }
        if (*it == 1) {
            it = numbers.erase(it);
        } else {
            it++;
        }

    }

    for (std::list<int>::iterator it = numbers.begin(); it != numbers.end();
            it++) {
        std::cout << *it << '\n';
    }

    return 0;
}

Solution

  • You can probably do this if iterators are required:

    // ...
    
    std::list<int>::iterator it = ++numbers.begin();
    numbers.insert(it, 100);
    std::cout << "Current element is: " << *it << '\n';
    
    std::list<int>::iterator eraseIt = ++numbers.begin();
    eraseIt = numbers.erase(eraseIt);
    std::cout << "erasing at element: " << *eraseIt << '\n';
    
    it = numbers.begin();
    while (it != numbers.end())
    {
        if (*it == 2) {
            numbers.insert(it, 1234);
        }
        if (*it == 1) {
            it = numbers.erase(it);
        }
        else {
            ++it;
        }
    }
    
    for (auto& i : numbers)
    {
        std::cout << i << std::endl;
    }
    
    // ...