Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;模板函数检查唯一向量_C++_Templates_Vector_Stream_Boolean - Fatal编程技术网

C++ C++;模板函数检查唯一向量

C++ C++;模板函数检查唯一向量,c++,templates,vector,stream,boolean,C++,Templates,Vector,Stream,Boolean,我试图编写一个名为unique()的模板函数,该函数只使用、和头来检测std::vector是否只有唯一的元素 template <typename T> bool unique(const std::vector<T>& container){} 模板 bool unique(const std::vector&container){} 我如何才能做到这一点?std::设置其他{container.begin(),container.end()); std:

我试图编写一个名为
unique()
的模板函数,该函数只使用
头来检测
std::vector
是否只有唯一的元素

template <typename T>
bool unique(const std::vector<T>& container){}
模板
bool unique(const std::vector&container){}
我如何才能做到这一点?

std::设置其他{container.begin(),container.end());
std::set<T> other{ container.begin(), container.end() );
return other.size() < container.size();
返回other.size()
你也可以早点休息

std::set<T> other;
for (auto&& e:container)
  if (!other.insert( e ).second)
    return false;
return true;
std::设置其他;
用于(自动(&e:容器)
如果(!其他.插入(e).秒)
返回false;
返回true;

如果您可以使用
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();
}
模板
布尔唯一(常量标准::向量和容器)
{
return container.size()==std::set{container.begin(),container.end()}.size();
}

你尝试了什么?对你来说明显的东西对其他人来说根本不明显。你遇到了什么问题?想想
std::set
是如何工作的,添加一些迭代器魔法,解决方案可能是一行。哦,我现在明白了。set流非常简单useful@cppp2020是的,迭代器对构造函数非常有用应该注意的是,这是O(NlogN)复杂度,并且使用O(N)空间。虽然效率不高,但效果相当好。一个
std::unordered_集
将其归结为O(N)复杂性。这个问题几乎是重复的。至少答案肯定是:请注意,集合要求对象不具有可比性。因此,您需要为不具有可比性的T提供这一点。复制向量、排序和查找顺序匹配可能会更快。集合执行大量堆分配。