You can construct a std::unordered_set from each vector, then compare those, as shown in the code snippet below:#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;}但是,有几点需要牢记:However, there are some points to bear in mind:对于自定义类型对象的向量,您需要为该类型提供一个 operator == (但是无论如何都必须这样做,或者如何确定两个向量具有相同的内容).包含重复项的向量将创建删除了重复项的集合:因此, {1、2、2、3} 将显示等于 {1、2、3} .您还需要为您的自定义类型提供 std:hash .对于一个简单的类, bob (只包装一个整数),该散列和所需的 operator == 可以定义如下;您可以在上面的示例中用< bob> 替换上例中的< int> 专业化,它将起作用.(这篇 cppreference文章详细介绍了有关哈希的信息.)For vectors of custom type objects, you would need to provide an operator== for that type (but that would have to be done anyway, or how can you say if the two vectors have the same contents).Vectors that containing duplicate entries will create sets that have those duplicates removed: Thus, {1, 2, 2, 3} will show equal to {1, 2, 3}.You will also need to provide a std:hash for your custom type. For a trivial class, bob, which just wraps an integer, that hash, and the required operator==, could be defined as shown below; you can then replace the <int> specializations in the above example with <bob> and it will work. (This cppreference article explains more about the hash.)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); }}; 这篇关于如何比较两个向量的相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-28 04:07