2

到目前为止,我有这个功能:

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

此函数返回来自 v 的元素的排序向量,没有重复。

有没有更紧凑的写法?我读过关于 std::unique 的内容,但这涉及编辑我无法做的向量。

4

2 回答 2

6

由于您无论如何都在复制向量,只需进行复制,然后对结果进行排序和唯一化:

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;
}
于 2013-05-30T22:54:30.903 回答
3

我读过关于 std::unique 的内容,但这涉及编辑我无法做的向量。

先复制一份吧!然后你可以unique/erase按照通常的方式使用。在 C++03 中,你会写:

std::vector<int> f(const std::vector<int>& v)
//                 ^^^^^ you won't modify v, so make it obvious!
{
    std::vector<int> result(v); // copy the vector
    std::sort(result.begin(),result.end()); // sort it first so that std::unique can work
    std::erase(std::unique(result.begin(),result.end()), result.end()); // just keep the unique elements
    return result;
}

如果您使用 C++11,那么您可以利用移动语义和按值传递参数(将右值传递给函数时效率更高,对左值也同样有效),这也允许您直接修改参数:

std::vector<int> f(std::vector<int> v)
//                 ^^^^^^^^^^^^^^^^ pass by value
{
    std::sort(v.begin(),v.end()); // sort it first so that std::unique can work
    std::erase(std::unique(v.begin(),v.end()), v.end()); // just keep the unique elements
    return v;
}

感谢@DavidBrown 和@chris,我倾向于忽略这个 C++11 习语,因为我还不习惯它。

于 2013-05-30T22:53:52.257 回答