c++ vector last element code example

Example 1: access last element in vector in c++

vector<int> v;
cout << v[v.size() - 1];
cout << *(v.end() - 1);
cout << *v.rbegin();
// all three of them work

Example 2: vector last c++

// vector::back
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  myvector.push_back(10);

  while (myvector.back() != 0)
  {
    myvector.push_back ( myvector.back() -1 );
  }

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size() ; i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

Example 3: c++ vector.back

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> myvector;
  
  //add 2 to the back
  myvector.push_back(2);
  
  std::cout << myvector.back() << std::endl; //this will print 2
  
  myvector.push_back(46);
  std::cout << myvector.back() << std::endl; //prints 46
  
  return 0;
  
}

/*Output
2
46
*/

Example 4: c++ access second last element of vector

arr2.rbegin()[1] // rbegin() is reverse order starting at 0 for last element, 1 for second-last

Example 5: c++ get last element in vector

std::v.back()

Tags:

Cpp Example