Search code examples
c++foreachstdset

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


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?


Solution

  • 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;
    }