Create ranges from an array of integers Given an array of ints, return a string identifying the range of
  numbers.
  
  Example:
  
  
  Input arr - [0 1 2 7 21 22 1098 1099] 
  Output - "0-2,7,21-22,1098-1099"
  


Is there any improvement possible in this implementation?

#include&lt;iostream&gt;
#include&lt;vector&gt;
#include&lt;algorithm&gt;
#include&lt;sstream&gt;

std::string  range_creator(std::vector&lt;int&gt; &amp; vec)
{
    std::sort(std::begin(vec),std::end(vec));

    int first=vec.at(0);
    int prev=first-1;

    std::stringbuf buffer;
    std::ostream os (&amp;buffer);

    for(auto &amp;x : vec)
    {
       if(++prev == x)
           continue;
        else
        {

           if(first != --prev)
           {               
               os &lt;&lt; first&lt;&lt;"-"&lt;&lt;prev&lt;&lt;",";
               prev=x;
               first=x;
           }
           else
           {
               os&lt;&lt;first&lt;&lt;",";
               prev=x;
               first=x;
           }


        }

    }
    if(first != prev)
    {
        os&lt;&lt;first&lt;&lt;"-"&lt;&lt;prev;
    }
    else
    {  
       os&lt;&lt;first; 
    }
    return buffer.str();
}

int main()
{
    std::vector&lt;int&gt; vec={0,1,2,7,8,9,10,21,22,23,24,25,27,1098,1099,1100,2000};
    std::cout&lt;&lt;range_creator(vec);

    return 0;
}
You can make good use of std::adjacent_find. Like this:

std::string range_creator(std::vector&lt;int&gt; &amp; vec)
{
    auto first = std::begin(vec), last = std::end(vec);
    if(first == last)
        return "";
    std::sort(first, last);
    std::stringbuf buffer;
    std::ostream os (&amp;buffer);
    while(true)
    {
        auto mid = std::adjacent_find(first, last,
                [](int x, int y){ return x + 1 != y; });
        if(mid == last)
            break;
        if(first == mid)
            os &lt;&lt; *first &lt;&lt; ",";
        else
            os &lt;&lt; *first &lt;&lt; "-" &lt;&lt; *mid &lt;&lt; ",";
        first = ++mid;
    }
    if(first == --last)
        os &lt;&lt; *first;
    else
        os &lt;&lt; *first &lt;&lt; "-" &lt;&lt; *last;
    return buffer.str();
}


I think my code is still subject to further improvements, but I'm no expert, so I'll leave it to the community.