Victoria Hust
5
Q:

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
3
#include<iostream>
/*To get the last element of the array we first get the size 
    of the array by using sizeof().  Unfortunately, this gives 
    us the size of the array in bytes.  To fix this, we divide
    the size (in bytes) by the size of the data type in the array.
    In our case, this would be int, so we divide sizeof(array) 
    by sizeof(int).  Since arrays  start from 0 and not 1 we 
    subtract one to get the last element.
    -yegor*/
int array[5] = { 1, 2, 3, 4, 5 };
printf("Last Element of Array: %d", array[(sizeof(array)/sizeof(int))-1]);
0
// C++ program to delete last element 
// of a Set by passing its iterator 
  
#include <iostream> 
#include <set> 
using namespace std; 
  
// Function to print the set 
void printSet(set<int> myset) 
{ 
  
    // Get the iterator 
    set<int>::iterator it; 
  
    // printing all the elements of the set 
    for (it = myset.begin(); it != myset.end(); ++it) 
        cout << ' ' << *it; 
    cout << '\n'; 
} 
  
// Function to delete last element of set 
// using method 1 
void deleteByMethod1(set<int> myset) 
{ 
  
    // printing all the elements of the set 
    cout << "\nSet originally: "; 
    printSet(myset); 
  
    // Get the iterator 
    set<int>::iterator it; 
  
    // Get the positionOfElementToBeDeleted 
    // using method 1 
    it = prev(myset.end()); 
  
    // Erase the last element 
    // currently pointed by the iterator 
    myset.erase(it); 
  
    // printing all the elements of the set 
    cout << "Set after deletion: "; 
    printSet(myset); 
} 
  
// Driver code 
int main() 
{ 
    set<int> myset; 
  
    // Get the set 
    for (int i = 1; i < 10; i++) 
        myset.insert(i * 10); 
  
    // Method 1 to get positionOfElementToBeDeleted 
    deleteByMethod1(myset); 
  
    return 0; 
} 
0
// stack::top
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
  std::stack<int> mystack;

  mystack.push(10);
  mystack.push(20);
  // .top() gets the last/top element of stack c++
  mystack.top() -= 5;

  std::cout << "mystack.top() is now " << mystack.top() << '\n';

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

New to Communities?

Join the community