如何比较两个向量是否相等?

Ole*_*leg 5 c++ algorithm stl

我有以下程序:

std::vector<int> nums = {1, 2, 3, 4, 5};
std::vector<int> nums2 = {5, 4, 3, 2, 1};

bool equal = std::equal(nums.begin(), nums.end(), nums2.begin());
if (equal)
{
    cout << "Both vectors are equal" << endl;
}
Run Code Online (Sandbox Code Playgroud)

有两个向量具有相同的元素。std::equal 函数在这里不起作用,因为它按顺序进行并比较相应的元素。有没有一种方法可以检查这两个向量是否相等,并且在我的情况下无需排序即可获得 true ?在真实的例子中,我没有整数,而是作为指针相等进行比较的自定义对象。

Adr*_*ica 3

您可以从每个向量构造一个std::unordered_set,然后比较它们,如下面的代码片段所示:

#include <iostream>  
#include <vector>  
#include <unordered_set> 

using namespace std;

int main()
{
    std::vector<int> nums = { 1, 2, 3, 4, 5 };
    std::vector<int> nums2 = { 5, 4, 3, 2, 1 };
    std::vector<int> nums3 = { 5, 4, 9, 2, 1 };

    std::unordered_set<int> s1(nums.begin(), nums.end());
    std::unordered_set<int> s2(nums2.begin(), nums2.end());
    std::unordered_set<int> s3(nums3.begin(), nums3.end());

    if (s1 == s2) {
        std::cout << "1 and 2 are equal";
    }
    else {
        std::cout << "1 and 2 are different";
    }
    std::cout << std::endl;

    if (s1 == s3) {
        std::cout << "1 and 3 are equal";
    }
    else {
        std::cout << "1 and 3 are different";
    }
    std::cout << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,有一些要点需要牢记:

  1. 对于自定义类型对象的向量,您需要operator==为该类型提供一个(但无论如何都必须这样做,或者如何判断两个向量是否具有相同的内容)。
  2. 包含重复条目的向量将创建删除这些重复项的集合:因此,{1, 2, 2, 3}将显示等于{1, 2, 3}
  3. 您还需要std:hash为您的自定义类型提供一个。对于一个简单的类,bob,它只包装一个整数,该散列和所需的operator==, 可以定义如下;然后您可以将<int>上面示例中的专业化替换为<bob>,它将起作用。(这篇cppreference 文章解释了有关哈希的更多信息。)
class bob {
public:
    int data;
    bob(int arg) : data{ arg } { }
};
bool operator==(const bob& lhs, const bob& rhs)
{
    return lhs.data == rhs.data;
}
template<> struct std::hash<bob> {
    std::size_t operator()(bob const& b) const noexcept {
        return static_cast<size_t>(b.data);
    }
};
Run Code Online (Sandbox Code Playgroud)