C ++模板函数检查唯一矢量

问题描述 投票:-1回答:2

我正在尝试编写一个名为unique()的模板化函数,该函数仅使用std::vector<vector><set>标头来检测<iostream>是否仅具有唯一元素。

template <typename T>
bool unique(const std::vector<T>& container){}

我如何做到这一点?

c++ templates vector stream boolean
2个回答
4
投票

如果可以使用std::set,这实际上很容易。由于std::set仅存储唯一的项目,因此您可以从std::set创建std::vector并比较它们的大小。如果它们匹配,则向量具有唯一元素。看起来像

template <typename T>
bool unique(const std::vector<T>& container)
{
    return container.size() == std::set<T>{container.begin(), container.end()}.size();
}

2
投票
std::set<T> other{ container.begin(), container.end() );
return other.size() < container.size();

您也可以早点休息。

std::set<T> other;
for (auto&& e:container)
  if (!other.insert( e ).second)
    return false;
return true;
© www.soinside.com 2019 - 2024. All rights reserved.