自学内容网 自学内容网

Android常用C++特性之std::equal

声明:本文内容生成自ChatGPT,目的是为方便大家了解学习作为引用到作者的其他文章中。

std::equal 是 C++ 标准库中的一个算法,用于比较两个范围内的元素是否相等。它可以用于检查两个容器或数组的内容是否完全相同。

语法

#include <algorithm>

template <class InputIt1, class InputIt2>
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2);

template <class InputIt1, class InputIt2, class BinaryPredicate>
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p);

参数

  • first1, last1:第一个范围的迭代器,定义开始和结束位置。
  • first2:第二个范围的开始迭代器。
  • p(可选):一个接受两个元素并返回布尔值的二元谓词,用于自定义比较逻辑。

返回值

返回 true 如果两个范围内的元素相等,返回 false 否则。

示例

1. 比较两个向量
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec1 = {1, 2, 3, 4, 5};
    std::vector<int> vec2 = {1, 2, 3, 4, 5};
    std::vector<int> vec3 = {1, 2, 3, 4, 6};

    // 比较 vec1 和 vec2
    if (std::equal(vec1.begin(), vec1.end(), vec2.begin())) {
        std::cout << "vec1 and vec2 are equal." << std::endl;
    } else {
        std::cout << "vec1 and vec2 are not equal." << std::endl;
    }

    // 比较 vec1 和 vec3
    if (std::equal(vec1.begin(), vec1.end(), vec3.begin())) {
        std::cout << "vec1 and vec3 are equal." << std::endl;
    } else {
        std::cout << "vec1 and vec3 are not equal." << std::endl;
    }

    return 0;
}

输出:

vec1 and vec2 are equal.
vec1 and vec3 are not equal.
2. 使用自定义比较函数
#include <iostream>
#include <vector>
#include <algorithm>

bool customCompare(int a, int b) {
    return (a % 10) == (b % 10); // 比较最后一位数字
}

int main() {
    std::vector<int> vec1 = {11, 22, 33};
    std::vector<int> vec2 = {1, 2, 3};

    // 使用自定义比较函数
    if (std::equal(vec1.begin(), vec1.end(), vec2.begin(), customCompare)) {
        std::cout << "vec1 and vec2 are equal based on custom comparison." << std::endl;
    } else {
        std::cout << "vec1 and vec2 are not equal based on custom comparison." << std::endl;
    }

    return 0;
}

输出:

vec1 and vec2 are equal based on custom comparison.

总结

  • std::equal 是用于比较两个范围内元素是否相等的标准算法。
  • 支持自定义比较逻辑,使其适用于不同的数据类型和比较需求。
  • 适合用于检查数组、向量、列表等容器的内容是否一致。

原文地址:https://blog.csdn.net/yzq_yezhiqiang/article/details/142553786

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!