Object of Affection for loops

https://www.codecademy.com/courses/learn-c-plus-plus/projects/cpp-dating-profile

Step 10 under hints it gives an example of a “for” loop and I don’t believe I’ve seen one declared this way and I don’t quite understand the underlying mechanics of what it’s trying to do.

for (std::string hobby : hobbies) {

hobby_string += " - " + hobby + "\n";

}

It declares string “hobby” and then a colon. Is this saying iterate through vector “hobbies” and “hobby” will equal whatever value is in the current slot of “hobbies” each time it loops? Seems logical, but I feel like I don’t have a complete grasp of what all can be done when declaring a for loop in this way.

It’s a range based for loop, it’s just more convenient/readable for looping over every element in a range/sequence. Page describes it better than me with examples- Range-based for loop (since C++11) - cppreference.com

2 Likes

Thank you for your help!

1 Like