C++标准库常用的遍历和查找算法

1.常用遍历算法

1.for_each

C++的std::for_each算法是标准库中的一个迭代器算法,它对容器或范围内的每个元素执行指定的操作。这个算法特别适用于你想要对容器内的每个元素应用同一个操作,但操作本身不需要积累结果(例如累加或查找最大值)的情形。std::for_each返回作用于每个元素的函数对象的副本。

基本语法如下:

template< class InputIt, class UnaryFunction>
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
  • InputIt first, InputIt last: 这是一个半开区间 [first, last),定义了要遍历的元素范围。
  • UnaryFunction f: 一个可调用的对象(如函数、lambda表达式或者函数对象),它接受一个参数(即容器中的元素类型)并对其进行操作。该对象会在区间内的每个元素上被调用。

示例:

#include <algorithm>
#include <iostream>
#include <vector>

void print(int i) {
    std::cout << i << ' ';
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // 使用std::for_each打印vector中的每个元素
    std::for_each(numbers.begin(), numbers.end(), print);

    return 0;
}

在这个例子中,print函数被传递给std::for_each,它会对numbers向量中的每个元素调用print函数,从而打印出向量中的所有数字。

自C++11起,还可以直接使用lambda表达式作为第三个参数,使得操作更加灵活:

std::for_each(numbers.begin(), numbers.end(), [](int i){ std::cout << i * 2 << ' '; });

这段代码会打印出向量中每个数字的两倍。

2.transform

C++的std::transform算法是标准库中的一个迭代器算法,用于将一个范围内或两个范围内的元素通过某个操作转换后存放到另一个范围。这个算法常用于对容器内容进行批量修改或计算转换后的结果。与std::for_each不同的是,std::transform通常涉及输入范围和输出范围,并且转换操作可能产生新的值。

基本语法如下:

// 单输入范围到单输出范围
template< class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first, UnaryOperation unary_op);

// 双输入范围到单输出范围
template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation>
OutputIt transform(InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt d_first, BinaryOperation binary_op);
  • 对于单输入范围版本:

    • InputIt first1, InputIt last1: 定义了输入范围。
    • OutputIt d_first: 指向输出范围的开始位置。
    • UnaryOperation unary_op: 一个可调用对象,接受一个输入范围的元素作为参数,并返回转换后的结果。
  • 对于双输入范围版本:

    • InputIt1 first1, InputIt1 last1, InputIt2 first2: 分别定义了两个输入范围。
    • 其余参数同上,但BinaryOperation binary_op接受两个输入范围对应位置的元素作为参数,并返回一个转换后的结果。

示例:

单输入范围示例,将一个vector中的每个元素平方后存入另一个vector:

#include <algorithm>
#include <iostream>
#include <vector>

int square(int x) {
    return x * x;
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::vector<int> squared;

    // 保留足够空间以避免插入时重新分配
    squared.resize(numbers.size());

    // 使用std::transform进行转换
    std::transform(numbers.begin(), numbers.end(), squared.begin(), square);

    for(int num : squared) {
        std::cout << num << ' ';
    }

    return 0;
}

双输入范围示例,将两个vector对应元素相加后存入第三个vector:

#include <algorithm>
#include <iostream>
#include <vector>

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

    // 使用std::transform进行转换,这里使用lambda表达式代替函数对象
    std::transform(vec1.begin(), vec1.end(), vec2.begin(), result.begin(), [](int a, int b){ return a + b; });

    for(int res : result) {
        std::cout << res << ' ';
    }

    return 0;
}

这些示例展示了如何使用std::transform进行简单的数值转换和组合操作。

2.常用查找算法

在C++标准库中,提供了多种查找算法来帮助处理容器或范围内的数据。以下是您提到的一些常用查找算法的简要说明:

1. find

std::find用于在一个范围内查找指定的值。如果找到该值,则返回指向该值的第一个匹配项的迭代器;如果没有找到,则返回表示范围末尾的迭代器。

基本用法:

template< class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value);

示例:

// 包含标准输入输出库、算法库和向量库
#include <iostream>
#include <algorithm>
#include <vector>

// 使用标准命名空间,简化代码中标准库函数的调用
using namespace std;

// 程序的主入口函数
int main(){
    // 初始化一个字符串变量name
    string name = "Felipe";

    // 查找字符串name中字符'F'的位置
    auto in = find(name.begin(), name.end(),'F');
    // 输出找到的字符
    cout << *in << endl;

    // 初始化一个整数向量V,并赋初值
    vector<int>V = {1,2,3,5,6,7};

    // 在向量V中查找数值1的位置
    auto it = find(V.begin(), V.end(),1);

    // 判断是否找到数值1,如果找到则输出相应信息
    if(it != V.end()){
        cout << "find 1" << endl;
    }

    // 程序正常结束
    return 0;
}

2. find_if

std::find_if类似于find,但它不是直接查找特定值,而是使用提供的谓词(如函数、lambda表达式)来测试每个元素,直到找到第一个使谓词返回true的元素。如果找到这样的元素,则返回指向它的迭代器;否则,返回last

基本用法:

template< class InputIt, class UnaryPredicate>
InputIt find_if(InputIt first, InputIt last, UnaryPredicate pred);

示例:

// Filename: find_example.cpp
// Created by 86189 on 2024/7/7.
//
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// 主函数,演示如何使用标准库函数find_if查找向量中第一个大于5的元素
int main() {
    // 初始化一个整数向量,包含1到6的几个数字,其中有重复
    vector<int> V = {1, 2, 3, 3, 4, 5, 6};

    // 使用find_if算法查找向量中第一个大于5的元素
    // find_if函数接受一个范围(向量的开始和结束迭代器)和一个谓词(用于判断条件的lambda表达式)
    // 这里lambda表达式返回值为true时意味着找到了满足条件的元素
    auto it = find_if(V.begin(), V.end(), [](const int &val) { return val > 5; });

    // 检查是否找到了满足条件的元素
    if (it != V.end()) {
        // 如果找到了,输出该元素的值
        cout << *it << endl;
    } else {
        // 如果没有找到,输出提示信息
        cout << "No element greater than 5 found." << endl;
    }

    return 0;
}

3. adjacent_find

std::adjacent_find用于查找序列中相邻重复的元素对。它返回一个指向序列中第一个重复元素的迭代器,如果序列中没有相邻的重复元素,则返回最后一个元素的下一个位置。

基本用法:

template< class InputIt >
InputIt adjacent_find( InputIt first, InputIt last );

template< class InputIt, class BinaryPredicate >
InputIt adjacent_find( InputIt first, InputIt last, BinaryPredicate pred );

第二个版本接受一个比较谓词。

示例:

// 包含标准输入输出库和向量库
#include <iostream>
#include <vector>
#include <algorithm>
// 使用标准命名空间,简化代码中标准库函数的调用
using namespace std;

// 程序入口函数
int main(){
    // 初始化一个整数向量v,包含一组数字
    vector<int>v = {0,1,3,4,5,5,7,7};

    // 使用adjacent_find函数查找向量v中相邻重复的元素
    // adjacent_find返回的是一个迭代器,指向第一个相邻重复元素的位置
    auto it = adjacent_find(v.begin(), v.end());
    // 如果找到相邻重复元素,输出该元素的值
    cout << *it << endl;

    // 使用lambda表达式作为谓词,查找向量v中相邻元素差值绝对值大于1的元素
    // 这里的lambda表达式接收两个int类型的引用,返回一个bool值
    // 它比较两个引用所指的元素的差值的绝对值是否大于1
    auto in = adjacent_find(v.begin(), v.end(),[](const int &val,const int &b){return (abs(b-val)>1);});
    // 如果找到满足条件的元素,输出该元素的值
    cout << *in << endl;

    // 程序正常结束
    return 0;
}
4. binary_search

std::binary_search在一个已排序的范围内查找特定值。如果找到了该值,则返回true;否则,返回false。这个算法假设范围是按升序排序的。

基本用法:

template< class ForwardIt, class T>
bool binary_search(ForwardIt first, ForwardIt last, const T& value);

template< class ForwardIt, class T, class Compare>
bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp);

第二个版本接受一个比较函数。

示例:

#include <iostream>
#include <set>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    // 使用set的查找,无需自定义比较函数,因为set本身就是有序的且默认升序
    set<int> s = {1, 2, 3, 4, 5, 6};
    if (binary_search(s.begin(), s.end(), 5)) {
        cout << "Found: " << 5 << endl; // 更正输出格式
    }

    // 对于vector,如果要使用非默认比较(例如降序),需要正确传递比较函数
    // 但是,注意binary_search要求容器是已排序的。先对vector排序
    vector<int> v = {1, 3, 6, 5, 8, 4, 6};
    sort(v.begin(), v.end(), [](const int &a, const int &b) { return a > b; }); // 先排序

    // 确保v是按所需顺序排序后,再使用binary_search
    if (binary_search(v.begin(), v.end(), 5, [](const int &a, const int &b) { return a > b; })) {
        cout << "Found: " << 5 << endl; // 更正输出格式
    } else {
        cout << "Not found: " << 5 << endl; // 添加未找到时的输出
    }

    return 0;
}

注意:

binary_search算法要求其操作的范围必须是已排序的,不论是否提供了第四个比较函数参数。这是因为binary_search的工作原理基于二分查找算法,该算法的前提是输入数据是有序的。提供自定义的比较函数(即第四个参数)是为了适应不同的排序逻辑(如降序、自定义排序依据等),而不是为了处理无序数据。

如果输入范围是无序的,即使你提供了比较函数,binary_search的结果也是未定义的,可能会导致错误的查找结果。因此,在调用binary_search之前,你应该确保范围内的元素是按照你所指定的比较规则排序的。在上面的例子中,对vector<int> v应用了sort函数配合同样的比较函数进行了排序,之后才进行binary_search,这是正确的做法。

5. count

std::count计算范围内与给定值匹配的元素数量。

基本用法:

template< class InputIt, class T>
typename std::iterator_traits<InputIt>::difference_type count(InputIt first, InputIt last, const T& value);

示例:

//
// Created by 86189 on 2024/7/7.
//
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

// 主函数,程序的入口点
int main(){
    // 初始化一个整数向量v,包含一组数字,用于后续的计数操作
    vector<int>v = {1,2,2,2,2,2,5,6,9,8};

    // 使用标准库函数count计算向量v中值为2的元素的数量,并输出结果
    cout << count(v.begin(), v.end(),2) << endl;
    
    return 0;
}

6. count_if

std::count_if类似于count,但它不是直接计数特定值,而是使用谓词来决定哪些元素应该被计数。

基本用法:

template< class InputIt, class UnaryPredicate>
typename std::iterator_traits<InputIt>::difference_type count_if(InputIt first, InputIt last, UnaryPredicate pred);

示例:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

// 主函数,程序的入口点
int main(){
    // 初始化一个整数向量,包含一组数字用于后续操作
    vector<int>v = {1,2,2,3,2,2,5,6,9,8};

    // 使用标准库函数count计算向量v中值为2的元素个数
    // 并将结果输出到标准输出流
    cout << count(v.begin(), v.end(),2) << endl;

    // 使用标准库函数count_if计算向量v中大于2的元素个数
    // 使用lambda表达式作为谓词,对每个元素进行判断
    cout << count_if(v.begin(), v.end(),[](const int &a){return a>2;});

    return 0;
}

这些算法是C++标准库 <algorithm> 头文件的一部分,为处理容器和数组提供了强大的工具。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FightingLod

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值