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

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

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

语法

cpp 复制代码
#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. 比较两个向量
cpp 复制代码
#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;
}

输出:

vbnet 复制代码
vec1 and vec2 are equal.
vec1 and vec3 are not equal.
2. 使用自定义比较函数
cpp 复制代码
#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;
}

输出:

vbnet 复制代码
vec1 and vec2 are equal based on custom comparison.

总结

  • std::equal 是用于比较两个范围内元素是否相等的标准算法。
  • 支持自定义比较逻辑,使其适用于不同的数据类型和比较需求。
  • 适合用于检查数组、向量、列表等容器的内容是否一致。
相关推荐
郝学胜_神的一滴1 小时前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
见过夏天17 小时前
C++ 基础入门完全指南
c++
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK3 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境3 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境3 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴4 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境6 天前
C++ 的Eigen 库全解析
c++
卷无止境6 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴6 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake