user3924427
user3924427

Reputation: 53

How to get the second last element of a set in C++?

Ex; We write for(int i=0;i<(somethin_length)-1;i++) How to do so using set?

Upvotes: 1

Views: 3804

Answers (1)

cdhowie
cdhowie

Reputation: 168988

If you have a set, just decrement the end iterator twice.

// Check that we have at least two elements first; if we don't have at least
// two then proceeding would cause undefined behavior.
if (some_set.size() >= 2) {
    auto it = some_set.end();
    --it;
    --it;

    // *it now refers to the second-to-last value
}

Upvotes: 3

Related Questions