mardi 6 août 2019

Ranged based for-loop: necessity of pointer variable as condition in if-statement

I dont understand why the condition of if-statement needs to be a pointer. I assumed a normal variable call will not give any complaints.

Was trying to learn about std::vector::erase from cppreference, got intrigued about the example there (https://en.cppreference.com/w/cpp/container/vector/erase)

#include <vector>
#include <iostream>

int main( )
{
    std::vector<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    for (auto &i : c) {
        std::cout << i << " ";
    }
    std::cout << '\n';
    // Erase all even numbers (C++11 and later)
    for (auto it = c.begin(); it != c.end(); ) {
        if (*it % 2 == 0) {
            it = c.erase(it); // THE LINE ABOVE THIS
        } else {
            ++it;
        }
    }
    for (auto &i : c) {
        std::cout << i << " ";
    }
    std::cout << '\n';
}

Output

0 1 2 3 4 5 6 7 8 9 
1 3 5 7 9 

Hope anyone could share an explanation or direct me to an available resource.

Aucun commentaire:

Enregistrer un commentaire