×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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

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

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.