首页 > 解决方案 > 使用 STL 查找容器是否包含重复值的有效方法?

问题描述

我很惊讶 STL 的算法部分没有 std::is_unique 。

我已经用 std::unique_copy 解决了这个值,但我发现它很差,因为当我真的只需要知道是否有重复值时它会执行内存分配。

我知道替代解决方案包括在插入 std::set 时进行迭代以查找重复但相同的故事。

是否有一种高效、优雅(即:一个只使用标准算法的班轮)解决方案?

std::vector<std::string> elements = { "foo", "bar", "foo"} ;

std::vector<std::string> uniquified;
std::unique_copy(cbegin(elements),cend(elements), std::back_inserter(uniquified));
   if (uniquified.size() != elements.size())
       return "Elements are not unique";

标签: c++

解决方案


推荐阅读