簡體   English   中英

C++ 模板函數檢查唯一向量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM