Welcome to our tutorial on “for each” in C++. By the end of this session, you will have a clear understanding of this powerful command in the C++ language. Our aim is to make a seemingly daunting subject accessible, engaging, and fun to learn!
Table of contents
What Is “for each” in C++?
In C++, “for each” is a loop statement, or to be technical, a range-based loop. It is used to iterate over elements in a range, such as an array, a list, or any collection of elements.
Why Should You Learn This?
The “for each” statement makes the code cleaner and easier to read. It can simplify and streamline your code, especially when dealing with collections of elements. Being familiar with “for each” comes in handy for creating efficient coding structures and algorithms.
What Can It Be Used For?
In the world of game development, array and list iteration are common scenarios where “for each” shines. Imagine you have a list of game characters that you need to update every frame. Or, consider a scenario where you have to search for a specific item in an array. “For each” can be a game-changer for these tasks!
Remember, mastering “for each” in C++ will greatly enhance your coding skills and overall programming fluency. So, let’s begin!
On our next post, we will explore the first section of this coding tutorial which will provide detailed code examples and explanations. It is going to be an exciting journey! So, get ready to take your programming skills to new heights with the power of “for each” in C++. Stay tuned!
Basic Usage of ‘for each’ in C++
The basic usage of “for each” in C++ involves providing a collection, like an array or list, and iterating over the items.
int main() { // An array of integers int numbers[] = {1, 2, 3, 4, 5}; // 'for each' loop for(int n : numbers) { cout << n << endl; } return 0; }
In the example above, we have a standard integer array named ‘numbers’. The “for each” loop makes it possible to iterate over each element in this array, in the given order.
Remember, the syntax is intuitive: for each element ‘n’ (which are integers, in our case) in the ‘numbers’ array, execute the body of the loop. In this case, it’s a simple cout statement to print out the number.
Using ‘for each’ with Other Data Types
The beauty of “for each” goes beyond just integers. It is also compatible with other data types. Here’s an example with a string array:
int main() { // An array of strings string fruit[] = {"Apple", "Banana", "Cherry", "Date"}; // 'for each' loop for(string f : fruit) { cout << f << endl; } return 0; }
In this example, the range is an array of strings. The “for each” loop iterates over each string in the ‘fruit’ array in turn and prints it out.
Nesting ‘for each’ Loops
Just like traditional for loops, you can nest “for each” loops within each other:
int main() { // 2D array of integers int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Nested 'for each' loops for(auto& row : matrix) { for(int num : row) { cout << num << " "; } cout << endl; } return 0; }
In this example, we have a two-dimensional array (a matrix). This scenario uses nested “for each” loops. The outer loop iterates over each row (which is itself an array), and the inner loop goes through each number in that row. This way, we have a clean and readable way to visit all the numbers in the matrix.
Work With Complex Data Structures
Don’t think for a moment that “for each” is only for simple collections! Here’s an example of “for each” being used with a vector of pairs.
#include int main() { // A vector of pairs std::vector<std::pair> students = { {"John", 85}, {"Emma", 95}, {"Sophia", 90} }; // 'for each' loop for(auto& s : students) { cout << s.first << ": " << s.second << endl; } return 0; }
In this case, we are dealing with a complex data structure: a vector of pairs. Each pair has a string and an integer, which we’re thinking of as a student’s name and their score. The “for each” loop goes through each pair, and we can access the elements of the pair using `s.first` and `s.second`.
Modify Elements in the Loop
In some situations, you need to not just view each item in a range, but also modify them. Here’s an example where the “for each” loop modifies the array elements:
int main() { // An array of integers int numbers[] = {1, 2, 3, 4, 5}; // 'for each' loop for(int& n : numbers) { n *= 2; } // Print the modified array for(int n : numbers) { cout << n << endl; } return 0; }
You’ve noticed the use of `&` before `n` in the loop. This means we’re dealing with a reference, not a copy of the array element. Hence, when we change `n`, it changes the corresponding element directly in the array.
Using ‘for each’ with Maps
Yes, “for each” works with maps as well! Take a look at this example:
#include <map> int main() { // A map of string-integer pairs std::map studentScores = { {"Lisa", 87}, {"Tom", 92}, {"Andy", 78} }; // 'for each' loop for(auto& pair : studentScores) { cout << pair.first << ": " << pair.second << endl; } return 0; }
Here, we have a map where each item is a pair. The “for each” loop can iterate over each pair in the map, giving us access to both the key and the value.
In conclusion, the “for each” loop in C++ is not only for basic purposes, but also widely adaptable to handle complex situations with elegance and simplicity. This versatility makes it an incredibly valuable tool in your C++ toolbox. So, make sure to utilize what you’ve learned today in your next coding session!
Using ‘for each’ with Enums
Did you know you could also use the “for each” with enums? However, because C++ does not offer direct support for looping over enum values, we can work around by using a vector to store the enum values. Here is how:
enum Fruit {Apple, Banana, Cherry, Date}; int main() { // Vector storing enum values vector<Fruit> fruit = {Apple, Banana, Cherry, Date}; // 'for each' loop for(Fruit f : fruit) { cout << f << endl; } return 0; }
In the above code, we are experiencing the flexibility of “for each” even further. We have an enum `Fruit` and we want to iterate over its elements. By storing the enum values in a vector, we make this possible with the “for each” loop.
Using Lambda Expressions with “for each”
We can combine the “for each” loop with Lambda expressions to write compact and efficient codes. Lambda expressions are a big topic on their own, but here is a simple example:
#include int main() { // A vector of integers vector<int> numbers = {1, 2, 3, 4, 5}; // 'for each' with lambda for_each(begin(numbers), end(numbers), [] (int n) { cout << n * n << endl; }); return 0; }
In this instance, we put to use the `for_each` algorithm which accepts two iterators (begin and end of the ‘numbers’ vector) and a lambda function that defines what to do with each number in the vector. Here, it simply prints out the square of each number.
Using ‘for each’ with Multi-dimensional Arrays
‘For each’ can also function with multi-dimensional arrays. However, for a multi-dimensional array, the element type is actually an array, hence, you must define the variable accordingly in the loop:
int main() { // 2D array of integers int numbers[2][3] = {{1, 2, 3}, {4, 5, 6}}; // Outer 'for each' loop for (const auto &row : numbers) { // Inner 'for each' loop for (int n : row) { cout << n << " "; } cout << endl; } return 0; }
In this example, ‘row’ represents each row of integers in the 2D array and needs to be treated as an array in the loop. Hence, ‘row’ is declared as an array in the outer “for each” loop, iterating over the rows, while the inner loop iterates over each number in the given row.
Using ‘for each’ with Structs
Finally, let’s explore how we can use ‘for each’ with Structs:
struct Student { string name; int score; }; int main() { // Array of Student structs Student students[] = { {"John", 85}, {"Emma", 95}, {"Sophia", 90} }; // 'for each' loop for(const auto &s : students) { cout << s.name << ": " << s.score << endl; } return 0; }
Here, we’ve got an array of ‘Student’ structs. For each ‘Student’ s in our array, the “for each” loop can access its fields using the dot operator, demonstrating how naturally “for each” can work with a variety of types and data structures.
We hope these examples showcased the versatility of the “for each” loop in C++ and how mastering it will take your programming skills to the next level. Stay tuned for more helpful and engaging programming tutorials from Zenva Academy!
Where to Go Next?
Fantastic job on working your way through “for each” in C++. You’re well on your way to mastering this powerful programming language. But your journey doesn’t end here. The next step in honing your abilities and building a robust skillset is to put what you’ve learned into practice while discovering new concepts.
At Zenva’s C++ Programming Academy, we provide comprehensive courses that delve into C++ programming and beyond in an accessible and engaging format. Not only will you solidify your understanding of C++ syntax and principles, but you’ll also explore exciting elements like game mechanics, and graphics and audio using SFML. The courses also present an opportunity to build a portfolio of real C++ projects, setting you up for success in your future endeavors.
For a broader range of subjects to explore, you can find additional learning materials within our C++ Courses collection. Regardless of where you are on your coding journey, Zenva caters to all levels, providing courses to take you from beginner to professional.
So, why wait? Your exciting journey into C++ programming and beyond awaits. Let’s continue learning together!
Conclusion
Taking control of “for each” in C++ will leave you well-prepared to tackle an array of game development projects with confidence and efficiency. Remember, in providing you with these lessons, it’s our aim at Zenva to make your learning journey smooth, engaging, and fun.
Through our C++ Programming Academy, you can dive further into the world of game development and coding tutorials. Our high-quality, easy-to-follow tutorials will empower you with the skills you need to master not only C++, but also other key programming languages and concepts. Happy coding!