到目前为止我有这个功能:
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 中无重复元素的排序 vector 。
有没有更紧凑的写法?我读过有关 std::unique 的内容,但这涉及编辑我无法做到的 vector 。
最佳答案
因为无论如何你都在复制 vector ,所以只需复制,然后对结果进行排序和唯一:
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;
}
关于c++ - 创建没有重复项的新排序 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16847071/