我不想更改 vector 或创建一个删除了重复项的新 vector 。我只想检查重复项,例如:
{90, 80, 70, 60, 50, 40, 30, 20, 10, 10} -> true
{90, 89, 88, 87, 86, 85, 84, 83, 82, 81} -> false
最佳答案
由于 vector 已排序,因此可以检查两个相邻元素是否相等:
for (auto it = vec.begin() + 1; it != vec.end(); ++it)
{
if (vec[it] == vec[it - 1])
{
// duplicate
return true;
}
}
// no duplicate
return false;
您还可以使用std::adjacent_find将迭代器返回到 vector 中第一个重复项的第一个元素:
auto it = std::adjacent_find(vec.begin(), vec.end());
if (it == vec.end())
{
// no duplicate
return false;
}
// duplicate
return true;
关于c++ - 我怎么知道排序的 vector 在C++中是否有重复的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33051433/