c++ - 我怎么知道在 C++ 中排序的 vector 是否有重复值

标签 c++ vector stl

我不想更改 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/

相关文章:

c++ - 将提取的字符存储在字符串 vector 中

c++ - std::vector 内存处理

vector - VHDL 直接比较向量

c++ - 比较 C++ STL 列表迭代器

c++ - 如何循环遍历 std::set/add 条件中的元素到 std::for_each 而不是 vs2008 中的 std::set?

C++ 类成员的循环引用

c# - PInvoke "Attempted to read or write protected memory"

c++ - 从 Qml 传递到 C++ 的对象类型

C++ 将 CSV 文件解析为 vector vector : Loosing string 1st character

C++ 标准 :sort() using different criteria