How to detect if the current element in a set is the last element?

72 views Asked by At

I have a foreach loop that goes though a std::set that looks like

for (auto& line : lines){
    //use line
    bool end = /* Check if line is the last element */
}

With a std::vector I could check &line == &lines.back();

Is there a way I can do something similar for a std::set?

3

There are 3 answers

1
AudioBubble On BEST ANSWER

zneak has some pretty good ideas, but here's one involving iterators in the loop:

std::set<std::string> lines;
lines.insert("Hello");
lines.insert("Thar");
lines.insert("How");
lines.insert("Goes");
lines.insert("It");
for (const auto& line : lines) {
    auto it = lines.find(line);
    it++;
    std::cout << std::boolalpha << (it == lines.end()) << std::endl;
}
0
zneak On

No, because a set doesn't have a front or a back. However, you could if you used iterators:

for (auto iter = lines.begin(); iter != lines.end(); iter++)
{
    bool end = iter + 1 == set.end();
}

Alternatively, you could count how many items you've iterated through:

size_t count = 0;
for (auto& line : lines)
{
    count++;
    if (count == set.size()) // this is the last element
}
0
Daniel On

How about this way,

auto iter = lines.cend();
if (iter!=lines.cbegin())
    --iter;
for (auto &line : lines)
{
    if (*iter==line) // end of the set
    {}
}