如何在c++中检查一个向量是否是另一个向量的子集
How to check whether a vector is a subset of another in c++
我试图找到一种简单的方法来检查向量是否是另一个向量的子集,而不排序向量中元素的顺序。两个向量都包含随机数元素
std::includes
似乎只适用于排序范围。我怎样才能做到这一点呢?
复制矢量。整理副本。然后在副本上使用std::includes
。
template <typename T>
bool IsSubset(std::vector<T> A, std::vector<T> B)
{
std::sort(A.begin(), A.end());
std::sort(B.begin(), B.end());
return std::includes(A.begin(), A.end(), B.begin(), B.end());
}
我的回答假设当你说"子集"时,你实际上是在寻找更多的"子字符串"的等量;即在搜索过程中保持元素的顺序。
最终,我看不出你怎么能在任何低于O(n*m)
的情况下做到这一点。考虑到这一点,您可以非常简单地滚动自己的:
template <typename T1, typename T2>
bool contains(std::vector<T1> const& a, std::vector<T2> const& b) {
for (typename std::vector<T1>::const_iterator i = a.begin(), y = a.end(); i != y; ++i) {
bool match = true;
typename std::vector<T1>::const_iterator ii = i;
for (typename std::vector<T2>::const_iterator j = b.begin(), z = b.end(); j != z; ++j) {
if (ii == a.end() || *j != *ii) {
match = false;
break;
}
ii++;
}
if (match)
return true;
}
return false;
}
现场演示。
(你可以在模板参数上更有创意)
这是假设重复项无关紧要的。因此,如果向量a中有两个数字99的实例,那么只要向量b至少有一个数字99的实例,那么它将被声明为一个子集。
bool isSubset(const std::vector<int>& a, const std::vector<int>& b)
{
for (std::vector<int>::const_iterator i = a.begin(); i != a.end(); i++)
{
bool found = false;
for (std::vector<int>::const_iterator j = b.begin(); j != b.end(); j++)
{
if (*i == *j)
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
无需排序…
template <typename T>
bool isSubsetOrEqual(std::vector<T> const& a, std::vector<T> const& b) {
for(auto const& av:a){
if(std::find(b.begin(),b.end(),av)==b.end())
return false;
}
return true;
}
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 获取向量C++中第一个值和最后一个值的和
- 从多个源构造一个对象,包括一个对象向量
- 为什么一个向量上的多线程操作很慢
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 将一个向量插入另一个向量的某个位置
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 将指向给定子类的指针从一个向量复制到另一个向量
- 如何创建一个类,以便向量工作 std::vector<MyClass<int>> v{ 1,2,3 };
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针
- 紧凑向量一个小的内存足迹向量