Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new sorted vector without duplicates

So far i have this function:

std::vector<int> f(std::vector& v)
{
    std::vector<int> result;
    for(unsigned x = 0; x < v.size(); x++)
    {
        std::vector<int>::iterator location = std::find(result.begin(),result.end(),v[x]);
        if(location == result.end())
        {
            result.push_back(this->v[x]);
        }
    }
    std::sort(result.begin(),result.end());
    return result;
}

This function returns a sorted vector of elements from v without duplicates.

Is there a more compact way of writing this? I've read about std::unique,but this involves editing the vector which i cannot do.

like image 526
Bartlomiej Lewandowski Avatar asked Aug 01 '26 10:08

Bartlomiej Lewandowski


1 Answers

Since you're copying the vector anyway, just do the copy, then sort and unique the result:

std::vector<int> f(std::vector<int> v) { 
    using std::begin;
    using std::end;

    std::sort(begin(v), end(v));
    v.erase(std::unique(begin(v), end(v)), end(v));
    return v;
}
like image 55
Jerry Coffin Avatar answered Aug 03 '26 00:08

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!