[Solved] Use of ” for(string str: tmp) ” in c++? [closed]


This is know as a for-each. It’ll iterate over the different elements of a data structure (for instance, a list, a vector, a set, …), allowing you to perform some operations on each elements. If you want to use it in c++ you will have to use c++11, but you can reach a similar behavior with an iterator based for loop.

Going with your for (string str : tmp) s.insert(str), here is a small description of each parts of the expression. tmp is the data structure over which you want to iterate. string str is the declaration that will be called for each elements in the data structure. The type declared should reflect what is in the data structure. This str variable will give you access to the data structure’s item in the loop’s “body”. The last part of the expression s.insert(str) is the loop’s “body” as in any regular for loop, but the coder chose to put it on the same line as the for.

In short, that loop inserts all the strings contained in tmp inside an object s with an insert method, probably another data structure.

1

solved Use of ” for(string str: tmp) ” in c++? [closed]