[英]C++ template function check unique vector
我正在嘗試編寫一個名為unique()
的模板化函數,它僅使用<vector>
、 <set>
和<iostream>
標<iostream>
檢測std::vector
只有唯一元素。
template <typename T>
bool unique(const std::vector<T>& container){}
我怎樣才能做到這一點?
如果您可以使用std::set
這實際上很容易。 由於std::set
只會存儲唯一項,因此您可以從std::vector
創建一個std::set
並比較它們的大小。 如果它們匹配,則向量具有唯一元素。 那看起來像
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.