确定矢量中是否存在重复项
Determine if there are duplicates in vector
我想确定向量中是否存在重复项。这里最好的选择是什么?
sort(arrLinkToClients.begin(), arrLinkToClients.end(), [&](const type1& lhs,const type1& rhs)
{
lhs.nTypeOfLink < rhs.nTypeOfLink;
});
auto it = unique(arrLinkToClients.begin(), arrLinkToClients.end(), [&](const type1& lhs, const type1& rhs)
{
lhs.nTypeOfLink == rhs.nTypeOfLink;
});
//how to check the iterator if there are duplicates ?
if (it)
{
//
}
"最佳"选项不存在。这取决于您如何定义"最佳"。
以下是一些解决方案,每种解决方案都有自己的优点和缺点:
Using map
template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
std::unordered_map<T, int> m;
for (const auto& e : v)
{
++m[e];
if (m[e] > 1)
return true;
}
return false;
}
Using set
template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
std::unordered_set<int> s;
std::copy(v.begin(), v.end(), std::inserter(s, s.begin());
return v.size() != s.size();
}
Using sort and adjacent_find (mutating range)
template <class T>
auto has_duplicates(std::vector<T>& v) -> bool
{
std::sort(v.begin(), v.end());
return std::adjacent_find(v.begin(), v.end()) != v.last();
}
Manual iteration with std::find
template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
for (auto it = v.begin(); it != v.end(); ++it)
if (std::find(it + 1, v.end(), *it) != v.end())
return true;
return false;
}
Manual iteration
template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
for (auto i1 = v.begin(); i1 != v.end(); ++i1)
for (auto i2 = i1 + 1; i2 != v.end(); ++i2)
if (*i1 == *i2)
return true;
return false;
}
如果没有重复项,则从unique
返回的迭代器是结束迭代器。所以:
if (it != arrLinkToClients.end())
cout << "Some duplicates found!";
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 地图计数确实很重要,或者只是检查是否存在
- C++中是否存在 std::conditional 的懒惰等价物?
- 无论如何,我可以确定构造函数是否存在吗?
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- 模板化检查是否存在带有参数列表的类成员函数?
- 是否存在包含负号的isdigit函数(过载)
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 检查编译时是否存在静态函数
- 向量是否存在行主要形式?
- 检查 TinyXML 中的元素是否存在
- 检测是否存在具有 C++17 的类成员
- 虚拟继承中是否存在多重继承?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符