如何检查两个std :: vector是否只包含相同的元素?

hkB*_*sai 4 c++ algorithm comparison stl vector

我需要一个算法或标准库函数来比较两个向量元素,如下所示:

class Utility
{
    template <class T>
    static bool CheckIfVectorsEquivalent(   const std::vector<T> & Vec1,
                                            const std::vector<T> & Vec2)
    {
        // ???
    }
};
Run Code Online (Sandbox Code Playgroud)

按照以下规格工作:

std::vector<int> v1, v2, v3, v4, v5, v6, v7, v8;

// Returns false when not all the elements are matching between vectors
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
v2.push_back(2);
v2.push_back(3);
v2.push_back(8);
Utility::CheckIfVectorsEquivalent(v1, v2);  // Must return false

// Returns true when all the elements match, even if the are not in the same order
v3.push_back(3);
v3.push_back(1);
v3.push_back(7);
v4.push_back(7);
v4.push_back(3);
v4.push_back(1);
Utility::CheckIfVectorsEquivalent(v3, v4);  // Must return true

// Returns false when one of the vectors is subset of the other one
v5.push_back(3);
v5.push_back(1);
v5.push_back(7);
v6.push_back(7);
v6.push_back(3);
v6.push_back(1);
v6.push_back(18);
v6.push_back(51);
Utility::CheckIfVectorsEquivalent(v5, v6);  // Must return false

// Returns true when the both vectors are empty
Utility::CheckIfVectorsEquivalent(v7, v8);  // Must return true
Run Code Online (Sandbox Code Playgroud)

有没有标准(用STL)这样做的方法?如果没有,我该怎么写这个算法?这让我很困惑.

Raf*_*cki 19

标准方法是对这两个向量==进行排序并使用运算符,该运算符比较相应的值.

实现此算法的示例解决方案是:

#include <vector>
#include <algorithm>

template<typename T>
bool compare(std::vector<T>& v1, std::vector<T>& v2)
{
    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());
    return v1 == v2;
}
Run Code Online (Sandbox Code Playgroud)

由于排序,其复杂度为O(n*log(n)).

  • 对于非常小的集合,执行O(n ^ 2)比较可能会更快,但仅适用于小集合.这个答案在99%的时间内都是准确的. (3认同)
  • @RafałRawicki:您是否只是因为把一个错误的答案变成另一个更糟糕的答案而受到欺负?您的答案仍然只对命令有意义,但是现在您已经删除了在这种情况下有关复杂性的有趣(正确的)注释。 (2认同)

Mar*_*low 13

如果您只能使用c ++ 11解决方案,那么std::is_permutation这正是您想要的

template <class FI1, class FI2>
bool is_permutation ( FI1 first, FI1 last, FI2 d_first );
Run Code Online (Sandbox Code Playgroud)

如果你不能那样做,那么在即将推出的1.50版本中,将会有

boost::algorithm::is_permutation
Run Code Online (Sandbox Code Playgroud)

具有相同的界面.

  • 标准说,std :: is_permutation,最多比较元素O(n ^ 2),所以这可能比较慢,但是写的很短. (2认同)