我不想更改 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++ - 我怎么知道在 C++ 中排序的 vector 是否有重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33051433/