Q:

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 ?

A:

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

A:

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

