The Wayback Machine - https://web.archive.org/web/20240118181952/https://www.geeksforgeeks.org/setkey_comp-in-c-stl/
Open In App
Related Articles

set::key_comp() in C++ STL

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

set::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container. By default, this is a less object, which returns the same as operator ‘<'. This object determines the order of the elements in the container. It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the first argument is considered to go before the second in the strict weak ordering it defines or false otherwise. Two elements of a set are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).

Syntax:

key_compare set_name.key_comp() 

Parameters: This function does not accept any parameter.

Return value: The function returns a copy of the comparison object used by the container.

Program to demonstrate the above function:




// C++ program to illustrate the
// set::key_comp() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // creating a set named 'a'
    set<int> a;
  
    set<int>::key_compare comp = a.key_comp();
  
    // Inserting elements into set
    for (int i = 0; i <= 10; i++)
        a.insert(i);
  
    cout << "Set a has the numbers: ";
  
    // stores the last value of the set
    int l = *a.rbegin();
  
    // initialising the iterator
    set<int>::iterator it = a.begin();
  
    // printing elements of all set
    do {
        cout << *it << " ";
    } while (comp(*(++it), l));
  
    return 0;
}


Output:

Set a has the numbers: 0 1 2 3 4 5 6 7 8 9
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 25 Jun, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads