如何在c++中检查一个向量是否是另一个向量的子集

How to check whether a vector is a subset of another in c++

本文关键字:向量 一个 是否是 另一个 子集 c++ 检查      更新时间:2023-10-16

我试图找到一种简单的方法来检查向量是否是另一个向量的子集,而不排序向量中元素的顺序。两个向量都包含随机数元素

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;
}