📜  C++中的for_each循环

📅  最后修改于: 2021-05-30 12:15:50             🧑  作者: Mango

除了诸如“ for,while和do-while”之类的通用循环技术外,C++在其语言中还使我们能够使用另一种功能,该功能解决了称为“ for-each”循环的相同目的。该循环接受一个在每个容器元素上执行的函数。此循环在头文件“ algorithm”中定义,因此必须包含此循环才能成功操作此循环。

  • 它用途广泛,即可以与任何容器一起使用。
  • 它减少了使用泛型for循环可能会犯的错误的机会
  • 它使代码更具可读性
  • for_each循环可提高代码的整体性能

句法:

for_each (InputIterator first, InputIterator last, Function fn)

strt_iter : The beginning position 
from where function operations has to be executed.
last_iter : This ending position 
till where function has to be executed.
fnc/obj_fnc : The 3rd argument is a function or 
an object function which operation would be applied to each element. 
CPP
// C++ code to demonstrate the
// working of for_each loop
 
#include
#include
#include
using namespace std;
 
// helper function 1
void printx2(int a)
{
    cout << a * 2 << " ";
}
 
// helper function 2
// object type function
struct Class2
{
    void operator() (int a)
    {
        cout << a * 3 << " ";
    }
} ob1;
 
 
int main()
{
     
    // initializing array
    int arr[5] = { 1, 5, 2, 4, 3 };
     
    cout << "Using Arrays:" << endl;
     
    // printing array using for_each
    // using function
    cout << "Multiple of 2 of elements are : ";
    for_each(arr, arr + 5, printx2);
     
    cout << endl;
     
    // printing array using for_each
    // using object function
    cout << "Multiple of 3 of elements are : ";
    for_each(arr, arr + 5, ob1);
     
    cout << endl;
     
    // initializing vector
    vector arr1 = { 4, 5, 8, 3, 1 };
     
    cout << "Using Vectors:" << endl;
     
     
    // printing array using for_each
    // using function
    cout << "Multiple of 2 of elements are : ";
    for_each(arr1.begin(), arr1.end(), printx2);
     
    cout << endl;
     
    // printing array using for_each
    // using object function
    cout << "Multiple of 3 of elements are : ";
    for_each(arr1.begin(), arr1.end(), ob1);
     
    cout << endl;
     
}


CPP
// C++ code to demonstrate the working
// of for_each with Exception
 
#include
#include
#include
using namespace std;
 
// Helper function 1
void printx2(int a)
{
    cout << a * 2 << " ";
    if ( a % 2 == 0)
    {
        throw a;
    }
     
}
 
// Helper function 2
// object type function
struct Class2
{
    void operator() (int a)
    {
        cout << a * 3 << " ";
        if ( a % 2 == 0)
        {
            throw a;
             
        }
    }
} ob1;
 
 
int main()
{
     
    // Initializing array
    int arr[5] = { 1, 5, 2, 4, 3 };
     
    cout << "Using Array" << endl;
     
    // Printing Exception using for_each
    // using function
    try
    {
        for_each(arr, arr + 5, printx2);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
    cout << endl;
     
    // Printing Exception using for_each
    // using object function
    try
    {
        for_each(arr, arr + 5, ob1);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
     
    // Initializing vector
    vector arr1 = { 1, 3, 6, 5, 1 };
     
    cout << "\nUsing Vector" << endl;
     
    // Printing Exception using for_each
    // using function
    try
    {
        for_each(arr1.begin(), arr1.end(), printx2);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
    cout << endl;
     
    // printing Exception using for_each
    // using object function
    try
    {
        for_each(arr1.begin(), arr1.end(), ob1);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
}


C++
#include 
#include 
using namespace std;
 
int main()
{
 
    vector vec{ 1, 2, 3, 4, 5 };
 
    // this increases all the values in the vector by 1;
    for_each(vec.begin(), vec.end(), [](int& a) { a++; });
 
    // this prints all the values in the vector;
    for_each(vec.begin(), vec.end(),
             [](int a) { cout << a << " " << endl; });
 
    return 0;
}


输出
Using Arrays:
Multiple of 2 of elements are : 2 10 4 8 6 
Multiple of 3 of elements are : 3 15 6 12 9 
Using Vectors:
Multiple of 2 of elements are : 8 10 16 6 2 
Multiple of 3 of elements are : 12 15 24 9 3 

异常和for_each

在异常的情况下,如果函数引发异常,则for_each循环也会引发异常并中断/终止循环。

CPP

// C++ code to demonstrate the working
// of for_each with Exception
 
#include
#include
#include
using namespace std;
 
// Helper function 1
void printx2(int a)
{
    cout << a * 2 << " ";
    if ( a % 2 == 0)
    {
        throw a;
    }
     
}
 
// Helper function 2
// object type function
struct Class2
{
    void operator() (int a)
    {
        cout << a * 3 << " ";
        if ( a % 2 == 0)
        {
            throw a;
             
        }
    }
} ob1;
 
 
int main()
{
     
    // Initializing array
    int arr[5] = { 1, 5, 2, 4, 3 };
     
    cout << "Using Array" << endl;
     
    // Printing Exception using for_each
    // using function
    try
    {
        for_each(arr, arr + 5, printx2);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
    cout << endl;
     
    // Printing Exception using for_each
    // using object function
    try
    {
        for_each(arr, arr + 5, ob1);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
     
    // Initializing vector
    vector arr1 = { 1, 3, 6, 5, 1 };
     
    cout << "\nUsing Vector" << endl;
     
    // Printing Exception using for_each
    // using function
    try
    {
        for_each(arr1.begin(), arr1.end(), printx2);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
    cout << endl;
     
    // printing Exception using for_each
    // using object function
    try
    {
        for_each(arr1.begin(), arr1.end(), ob1);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
}
输出
Using Array
2 10 4 
The Exception element is : 2
3 15 6 
The Exception element is : 2
Using Vector
2 6 12 
The Exception element is : 6
3 9 18 
The Exception element is : 6

使用Lambda:

随着引入lambda函数,可以很容易地将其用于内联整体,这对于希望使用函数式编程的人们来说非常紧凑且非常有用。

C++

#include 
#include 
using namespace std;
 
int main()
{
 
    vector vec{ 1, 2, 3, 4, 5 };
 
    // this increases all the values in the vector by 1;
    for_each(vec.begin(), vec.end(), [](int& a) { a++; });
 
    // this prints all the values in the vector;
    for_each(vec.begin(), vec.end(),
             [](int a) { cout << a << " " << endl; });
 
    return 0;
}
输出
2 
3 
4 
5 
6 
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”