Different ways to iterate over C++ Vector

vector is a data structure for maintaining a set of elements having a specific data type. We’ve already discussed C++ (STL) Vector in this post. However, here we’ll learn about various ways to iterate over a C++ Vector. (Some of the following ways could also be used with other C++ containers like list, queue, map etc.)

Iterating over vector using index
void printVectorUsingIndex (vector<int> v) {
    int n = (int) v.size();
    
    for (int i=0; i<n; i++) {
        cout<<v[i]<<" ";
    }
    
    cout<<endl;
}
Iterating over vector using iterator
void printVectorUsingIterator (vector<int> v) {
    vector<int>::iterator it;
    
    for (it = v.begin(); it != v.end(); it++) {
        cout<<(*it)<<" ";
    }
    
    cout<<endl;
}
Iterating over vector using auto
void printVector (vector<int> v) {
    
    for (auto val : v) {
        cout<<val<<" ";
    }
    
    cout<<endl;
}

Code Implementation

//
//  main.cpp
//  Iterating over a Vector
//
//  Created by Himanshu on 11/12/22.
//

#include <iostream>
#include <vector>
using namespace std;
 
void printVectorUsingIndex (vector<int> v) {
    int n = (int) v.size();
    
    for (int i=0; i<n; i++) {
        cout<<v[i]<<" ";
    }
    
    cout<<endl;
}

void printVectorUsingIterator (vector<int> v) {
    vector<int>::iterator it;
    
    for (it = v.begin(); it != v.end(); it++) {
        cout<<(*it)<<" ";
    }
    
    cout<<endl;
}

void printVector (vector<int> v) {
    
    for (auto val : v) {
        cout<<val<<" ";
    }
    
    cout<<endl;
}
 
int main () {
    
    // Initialisation
    vector<int> vec({10, 15, 25, 40, 50});
    
    cout<<"Iterating over vector using index:"<<endl;
    printVectorUsingIndex(vec);
    
    cout<<"Iterating over vector using iterator:"<<endl;
    printVectorUsingIterator(vec);
    
    cout<<"Iterating over vector using auto:"<<endl;
    printVector(vec);
    
    return 0;
}

Output

Iterating over vector using index:
10 15 25 40 50 
Iterating over vector using iterator:
10 15 25 40 50 
Iterating over vector using auto:
10 15 25 40 50 

Here’s a working example: Ideone

Leave a Reply

Your email address will not be published. Required fields are marked *