C++ 算法 中的 for_each函数

首页 / C++入门教程 / C++ 算法 中的 for_each函数

C++算法for_each()函数将函数func应用于从"first"到"last"参数内的所有元素。

for_each - 语法

template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function func);

for_each - 参数

first - 它指定列表中的第一个元素。

last  - 它指定列表中的最后一个元素。

func - 这是一元函数,可以接受参数内的参数。

for_each - 返回值

该函数返回" func"。

for_each - 例子1

#include <iostream>
#include <algorithm>
#include <vector>
void newfunction (int k)
{
	std::cout << " " <<k;
}
struct newclass
{
	void operator () (int k)
	{
		std::cout <<" "<<k;
	} 
}
newobject;
int main()
{
	std::vector<int> newvector;
	newvector.push_back(50);
	newvector.push_back(100);
	newvector.push_back(150);
	std::cout << "newvector contains:\n";
	for_each (newvector.begin () , newvector.end (), newfunction);
	std::cout<< "\n newvector contains:\n";
	for_each (newvector.begin (), newvector.end(), newfunction);
	std::cout<<"\n";
	return 0;
}

输出:

newvector contains: 50 100 150
newvector contains: 50 100 150

for_each - 例子2

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void printx1(int b)
{
    cout << b * 2 << " ";
}
struct Class1
{
    void operator() (int b)
    {
        cout << b * 3 << " ";
    }
} obj1;
int main()
{
    int ar[5] = { 6, 7, 8, 9, 10 };
      cout << "Using Arrays:" << endl;
    cout << "Multiple of 2 of elements are : ";
    for_each(ar, ar + 5, printx1);
     cout << endl;
    cout << "Multiple of 3 of elements are : ";
    for_each(ar, ar + 5, obj1);
    cout << endl;
    vector<int> ar1 = { 2,3,5,7,1 };
     cout << "Using Vectors:" << endl;
    cout << "Multiple of 2 of elements are : ";
    for_each(ar1.begin(), ar1.end(), printx1);
    cout << endl;
    cout << "Multiple of 3 of elements are : ";
    for_each(ar1.begin(), ar1.end(), obj1);
    cout << endl;
     }

输出:

Using Arrays:                                                                                                                  
Multiple of 2 of elements are : 12 14 16 18 20                                                                                 
Multiple of 3 of elements are : 18 21 24 27 30                                                                                 
Using Vectors:                                                                                                                 
Multiple of 2 of elements are : 4 6 10 14 2                                                                                    
Multiple of 3 of elements are : 6 9 15 21 3

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术领导力实战笔记 -〔TGO鲲鹏会〕

Netty源码剖析与实战 -〔傅健〕

图解 Google V8 -〔李兵〕

Vim 实用技巧必知必会 -〔吴咏炜〕

乔新亮的CTO成长复盘 -〔乔新亮〕

说透芯片 -〔邵巍〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

超级访谈:对话道哥 -〔吴翰清(道哥)〕

Midjourney入门实践课 -〔Jovi〕

好记忆不如烂笔头。留下您的足迹吧 :)