How can I check if I’m on the last element when iterating using foreach syntax [duplicate]

You can’t really. That’s kind of the point of range-for, is that you don’t need iterators. But you can just change your logic on how you print your comma to print it if it’s not first:

bool first = true;
for (auto& elem : item_vector) {
    if (!first) printf(", ");
    // print elem
    first = false;
}

If that’s the intent of the loop anyway. Or you could compare the addresses:

for (auto& elem : item_vector) {
    if (&elem != &item_vector.back()) printf(", ");
    // ...
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)