C++ || Snippet – Custom “For Each” Iterator Function For Arrays

Print Friendly, PDF & Email

A “For Each” algorithm is a function that iterates over all the elements contained in a storage collection, and calls a separate user defined function to manipulate each element within that collection.

The code demonstrated on this page is different from the STL for_each function in that this implementation is meant to work mainly on standard arrays.

The example below illustrates the “For Each” concept in a fully compilable and working demonstration. This example is trivial in that all it does is call a separate user defined function to display all of the contents within each array. This implementation revolves around using a simple function pointer and a series of void pointers.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Leave a Reply