C++ - Algorithm - Using the for_each() function

An example of how using the for_each() function.

Notice that you can have the same result with an iterator, here an example.

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

void myFunction(int myInt)
{
    std::cout << "myInt = " << myInt << std::endl;
}

int main()
{
    std::vector<int> myVector;
    std::vector<int>::iterator myIterator;
    int i;

    i = 0;
    while (i < 10)
    {
        myVector.push_back(i++);
    }
    for(myIterator = myVector.begin(); myIterator != myVector.end(); ++myIterator)
    {
        if (*myIterator == 2)
        {
            myVector.erase(myIterator);
            myVector.insert(myIterator,  80);
        }
    }
    std::for_each(myVector.begin(), myVector.end(), myFunction);
    return 0;
}
 
Result:
 
myInt = 0
myInt = 1
myInt = 80
myInt = 3
myInt = 4
myInt = 5
myInt = 6
myInt = 7
myInt = 8
myInt = 9
You are now able to use the for_each() algorithm function.
Well done, you made it! wink

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.