C++中for_each用法学习

转自:chatgpt

1.介绍

std::for_each 是 C++ 标准库中的一个算法,用于对指定范围内的元素执行指定的操作。它的一般形式如下:

template <class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f);
  • firstlast 是表示范围的迭代器,[first, last) 是待处理的元素范围。
  • f 是一个一元函数对象(或者函数指针),该函数对象接受迭代器范围内的每个元素并进行处理。

std::for_each 遍历指定范围内的每个元素,并对每个元素调用给定的一元函数。它不会改变元素的值,而是通过传递值给函数对象来实现对元素的操作。例子:

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

void printSquare(int x) {
    std::cout << x * x << " ";
}

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

    // 使用 std::for_each 打印每个元素的平方
    std::for_each(vec.begin(), vec.end(), printSquare);
    // 或者使用匿名函数
     std::for_each(vec.begin(), vec.end(), [](int x) { std::cout << x * x << " "; });
    return 0;
}

//输出
1 4 9 16 25

传递引用的case: https://www.zhihu.com/question/37435965

#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
#include <functional>

class Print
{
public:
    void print(std::vector<int>& vec) {
        std::cout << "print" << std::endl;
        vec.push_back(1);
    }
};
typedef std::shared_ptr<Print> PrintPtr;

int main()
{
    PrintPtr ptr = std::make_shared<Print>();
    std::vector<PrintPtr> vec = { ptr };
    std::vector<int> intvec;
    std::for_each(vec.begin(), vec.end(),
                  std::bind(&Print::print, std::placeholders::_1, std::ref(intvec)));
   //std::bind返回function类型,在for_each遍历vec时,print函数传入的对象就是ptr,对每个ptr调用print函数,绑定的参数是intvec的引用。
    std::cout << "intvec.size=" << intvec.size();
}

//结果
print
intvec.size=1

 

  

posted @ 2024-01-14 13:17  lypbendlf  阅读(262)  评论(0编辑  收藏  举报