我想确定 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)
{
//
}
最佳答案
“最佳”选项不存在。这取决于您如何定义“最佳”。
这里有一些解决方案,每个都有自己的优点和缺点:
使用 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;
}
使用集合
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();
}
使用 sort 和 adjacent_find(变异范围)
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();
}
使用 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;
}
手动迭代
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;
}
关于c++ - 判断vector是否有重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49252730/