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

后端 未结 12 1712
天命终不由人
天命终不由人 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<int> 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

    0 讨论(0)
  • 2020-11-29 16:28

    There's a couple of strong reasons to use iterators, some of which are mentioned here:

    Switching containers later doesn't invalidate your code.

    i.e., if you go from a std::vector to a std::list, or std::set, you can't use numerical indices to get at your contained value. Using an iterator is still valid.

    Runtime catching of invalid iteration

    If you modify your container in the middle of your loop, the next time you use your iterator it will throw an invalid iterator exception.

    0 讨论(0)
  • 2020-11-29 16:31

    I was surprised nobody mentioned that iterating through an array with an integer index makes it easy for you to write faulty code by subscripting an array with the wrong index. For example, if you have nested loops using i and j as indices, you might incorrectly subscript an array with j rather than i and thus introduce a fault into the program.

    In contrast, the other forms listed here, namely the range based for loop, and iterators, are a lot less error prone. The language's semantics and the compiler's type checking mechanism will prevent you from accidentally accessing an array using the wrong index.

    0 讨论(0)
  • 2020-11-29 16:32

    With STL, programmers use iterators for traversing through containers, since iterator is an abstract concept, implemented in all standard containers. For example, std::list has no operator [] at all.

    0 讨论(0)
  • 2020-11-29 16:34
     //different declaration type
        vector<int>v;  
        vector<int>v2(5,30); //size is 5 and fill up with 30
        vector<int>v3={10,20,30};
        
        //From C++11 and onwards
        for(auto itr:v2)
            cout<<"\n"<<itr;
         
         //(pre c++11)   
        for(auto itr=v3.begin(); itr !=v3.end(); itr++)
            cout<<"\n"<<*itr;
    
    0 讨论(0)
  • 2020-11-29 16:35

    Here is a simpler way to iterate and print values in vector.

    for(int x: A) // for integer x in vector A
        cout<< x <<" "; 
    
    0 讨论(0)
提交回复
热议问题