dimanche 26 janvier 2020

Vector iteration position in for loop

Let's say I have a C++ code:

std::vector<int> example = {0, 5, 10, 15, 20, 25, 45, 49};
int position = 0; // in-vector position

for (auto i : example) {
    if (i == 20) {
        position = ?
        break;
    };
}; 

How do I get position while in the cycle without using iterators or they are the only way? I know I can use default way like:

for (int i = 0; i < example.size(); ++i) {
    if (example[i] == 20) { position = i; break; }
};

But I'd love to keep using the (auto : ) scheme.

Thank you.

Aucun commentaire:

Enregistrer un commentaire