c++ last element code example

Example 1: how to get last element of set in c++

set<int> s = {1,2,3}
auto it = s.end();
it--;
cout<<*it<<"\n"; // This refers to last element of a set

Example 2: 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 3: c++ last element of array

int arr[10];
int len = sizeof(arr) / sizeof(arr[0]);

Tags:

Cpp Example