Bar*_*ski 2 c++ vector unique std
到目前为止,我有这个功能:
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;
}
Run Code Online (Sandbox Code Playgroud)
此函数返回v中元素的有序向量,不带重复项.
有更紧凑的写作方式吗?我读过有关std :: unique的内容,但这涉及到编辑我无法做到的向量.
既然您正在复制矢量,只需复制,然后对结果进行排序和唯一:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1212 次 |
| 最近记录: |