C++ vector index by number

Introduction

Vector elements are indexed, the first element has an index of 0.

Individual elements can be accessed via the subscript operator [element_index] or a member function at(element_index):

#include <iostream> 
#include <vector> 

int main() /*from  w ww  .  j  a v  a 2 s  .c  om*/
{ 
    std::vector<int> v = { 1, 2, 3, 4, 5 }; 
    std::cout << "The third element is:" << v[2] << '\n'; 
    std::cout << "The fourth element is:" << v.at(3) << '\n'; 
} 



PreviousNext

Related