Home » C++ STL

Access vector elements using for each loop in C++ STL

C++ STL | accessing vector elements: Here, we are going to learn how to access vector elements using a for each loop in C++ STL?
Submitted by IncludeHelp, on May 12, 2019

Accessing vector elements

Here, we are going to learn by an example – how to access vector elements using for each loop?

Note: There is no such for each loop in C++ STL, we can create it and access the elements by using the same type as the container type.

Read more: for each (range based loop in C++ STL)

Syntax to access vector elements using for each kind of loop

    for(type variable_name : vector_name){
	    //print the element using variable_name
    }

Here,

  • type – is the data type of the vector.
  • variable_name – is a temporary variable that which stores the elements one by one.
  • vector_name – is the name of the vector.

C++ STL program to access vector elements using for each loop

//C++ STL program to access vector elements 
//using for each loop
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //vector declaration
    vector<int> v1;

    //pushing the elements
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);

    //printing the vector elements
    //using for each kind of loop
    cout << "Vector v1 elements are: ";
    for (int element : v1)
        cout << element << " ";
    cout << endl;

    return 0;
}

Output

Vector v1 elements are: 10 20 30 40 50





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.