Happy Mittal
Happy Mittal

Reputation: 3747

Checking if current element is last element of set

I am trying to write a print function for set in C++, and this is what I wrote :

void print_set(set<int> &s)
{
    cout<<"{";
    for(auto it = s.begin() ; it!=s.end() ; ++it)
    {
        cout<<*it;
        if(it!=(s.end()-1)) //shows error here
            cout<<",";
    }
    cout<<"}";
}

But I am getting error. How can I check whether current element is last element or not ?

Upvotes: 2

Views: 1249

Answers (5)

Jarod42
Jarod42

Reputation: 217145

What I do in this case:

void print_set(const std::set<int>& s)
{
    const char* sep = "";
    std::cout << "{";
    for (int e : s)
    {
        std::cout << sep << e;
        sep = ", ";
    }
    std::cout << "}";
}

Upvotes: 1

Frerich Raabe
Frerich Raabe

Reputation: 94299

Simply check whether the next element equals the end:

auto next = it;
++next;
if (next != s.end())
    cout << ",";

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

You can only apply the ++ and -- operators on set iterators. Adding a number is not defined. You can make your code work like so:

void print_set(set<int> &s)
{
    cout<<"{";
    auto second_to_last = s.end();
    if (!s.empty()) {
      second_to_last--;
    }
    for(auto it = s.begin() ; it!=s.end() ; ++it)
    {
        cout<<*it;
        if(it!=second_to_last) {
            cout<<", ";
        } 
    }
    cout<<"}";
}

What this code does is essentially store an iterator to the second to last element once and then compare the element you have with it. Please note that second_to_last will not be accurate if the set is empty but the code will still work as expected.

Upvotes: 1

jrok
jrok

Reputation: 55395

May I suggest an alternative approach?

Print the comma before each element, except the first:

void print_set(set<int> &s)
{
    cout << "{";
    for(auto it = s.begin() ; it != s.end() ; ++it)
    {
        if(it != s.begin())
            cout << ", ";
        cout << *it;
    }
    cout << "}";
}

Upvotes: 3

Sneftel
Sneftel

Reputation: 41474

set's integers are not random-access, so you can't do arithmetic on them. Use std::prev instead.

Upvotes: 5

Related Questions