这篇文章将检查两个Vector在 C++ 中是否相等。
如果两个Vector以相同的顺序具有相同的内容,则称它们相等。如果两个Vector具有相同的内容但顺序不同,则它们不等于彼此的结果 []
运营商不同。在 C++ 中有很多方法可以检查两个Vector是否相等,下面将对此进行讨论。要检查两个Vector是否包含相同的内容但顺序不同,请在调用以下任何方法之前对两个Vector进行排序。
1.使用 ==
操作员
最简单的解决方案是使用 ==
检查两个容器的内容是否相等的运算符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <vector> int main() { std::vector<int> v1 = { 1, 2, 5, 3, 4, 5 }; std::vector<int> v2 = { 1, 2, 3, 5, 4, 5 }; if (v1 == v2) { std::cout << "Both vectors are equal"; } else { std::cout << "Both vectors are not equal"; } return 0; } |
输出:
Both vectors are not equal
2.使用 std::equal
功能
我们也可以使用 std::equal 算法来确定两个范围内的元素是否相等。如果第二个序列中的元素多于第一个序列中的元素,这可能会失败。因此,最好检查两个Vector的大小是否也相同。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <vector> template<typename T> bool isEqual(std::vector<T> const &v1, std::vector<T> const &v2) { return (v1.size() == v2.size() && std::equal(v1.begin(), v1.end(), v2.begin())); } int main() { std::vector<int> v1 = { 1, 2, 5, 3, 4, 5 }; std::vector<int> v2 = { 1, 2, 3, 5, 4, 5 }; if (isEqual(v1, v2)) { std::cout << "Both vectors are equal"; } else { std::cout << "Both vectors are not equal"; } return 0; } |
输出:
Both vectors are not equal
3.使用 std::mismatch
功能
最后,标准库提供了 std::mismatch 算法,它比较两个指定范围内的元素并返回一对指定它们不同的第一个位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <vector> template<typename T> bool isEqual(std::vector<T> const &v1, std::vector<T> const &v2) { auto pair = std::mismatch(v1.begin(), v1.end(), v2.begin()); return (pair.first == v1.end() && pair.second == v2.end()); } int main() { std::vector<int> v1 = { 1, 2, 5, 3, 4, 5 }; std::vector<int> v2 = { 1, 2, 3, 5, 4, 5 }; if (isEqual(v1, v2)) { std::cout << "Both vectors are equal"; } else { std::cout << "Both vectors are not equal"; } return 0; } |
输出:
Both vectors are not equal
这就是在 C++ 中确定两个Vector是否相等。