Iterate through a C++ Vector using a 'for' loop

后端 未结 12 1735
天命终不由人
天命终不由人 2020-11-29 16:02

I am new to the C++ language. I have been starting to use vectors, and have noticed that in all of the code I see to iterate though a vector via indices, the first parameter

12条回答
  •  无人及你
    2020-11-29 16:25

    Using the auto operator really makes it easy to use as one does not have to worry about the data type and the size of the vector or any other data structure

    Iterating vector using auto and for loop

    vector vec = {1,2,3,4,5}
    
    for(auto itr : vec)
        cout << itr << " ";
    

    Output:

    1 2 3 4 5
    

    You can also use this method to iterate sets and list. Using auto automatically detects the data type used in the template and lets you use it. So, even if we had a vector of string or char the same syntax will work just fine

提交回复
热议问题