检查std :: vector有重复项 [英] Check std::vector has duplicates

查看:885
本文介绍了检查std :: vector有重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查整数向量是否有重复项,如果有则必须返回true.所以我尝试做这样的事情:

I want to check if a vector of integers has any duplicates or not, and have to return true if it does. So I try to do something like this:

vector<int> uGuess = {1,2,3,3,4,5}
vector<int> a = uGuess;
sort(a.begin(), a.end());
bool d = unique(a.begin(), a.end());

这将不起作用,因为无法将unqiue分配为bool值. 我应该如何进行呢? 如果我要编写一个for循环来执行相同的操作,该怎么办?

And this will not work since unqiue cannot be assigned as a bool value. How should I proceed towards this? If I were to write a for loop to perform the same action, how should I do that?

推荐答案

在Google中寻找std::unique,我发现此页面 cplusplus:唯一.我在看 a)它做了什么

Looking in google for std::unique I found this page cplusplus : unique. I looked at a) what it did

从每个连续的组中删除除第一个元素外的所有元素

Removes all but the first element from every consecutive group

因此,它看起来像您想要的-删除重复项.

So it looks like it does what you want - removes the duplicates.

然后我查看返回的内容以及遇到问题的一些评论...

I then looks at what it returns, and some comments, coming across a problem...

返回值:对未删除的最后一个元素之后的元素的迭代器.

Return value : An iterator to the element that follows the last element not removed.

因此,unique的结果是一个序列,该序列不必与整个向量相同.

So the result from unique is a sequence which is not necessary the same as the whole vector.

如果未删除任何内容,则返回值将是向量的结尾.

If nothing was removed the return value would be the end of the vector.

所以

vector<int>::iterator it = std::unique( a.begin(), a.end() );
bool wasUnique = (it == a.end() );

或者对于C ++ 11

Or for C++11

auto it = std::unique( a.begin(), a.end() );
bool wasUnique = (it == a.end() );

最后,为使唯一功能正常工作,必须对向量进行排序,因此完整的代码应包含

Finally for the unique function to work, the vector needs to be sorted, so the complete code would include

sort(a.begin(), a.end());

例如

sort(a.begin(), a.end());
auto it = std::unique( a.begin(), a.end() );
bool wasUnique = (it == a.end() );

这篇关于检查std :: vector有重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆