我正在尝试编写一个名为unique()
的模板化函数,该函数仅使用std::vector
,<vector>
和<set>
标头来检测<iostream>
是否仅具有唯一元素。
template <typename T>
bool unique(const std::vector<T>& container){}
我如何做到这一点?
如果可以使用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();
}
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;