📜  在C++ STL中设置:: key_comp()

📅  最后修改于: 2021-05-30 03:04:06             🧑  作者: Mango

set :: key_comp()是C++ STL中的内置函数,该函数返回容器使用的比较对象的副本。默认情况下,这是一个less对象,其返回值与运算符相同。该对象确定容器中元素的顺序。它是一个函数指针或函数对象,它接受与容器元素相同类型的两个参数,并且如果认为第一个参数以它定义的严格弱顺序在第二个参数之前出现,则返回true,否则返回false。如果key_comp自反地返回false (即,不管这些元素作为参数传递的顺序),则认为集合中的两个元素是等效的。

句法:

key_compare set_name.key_comp() 

参数:该函数不接受任何参数。

返回值:该函数返回容器使用的比较对象的副本。

演示上述函数:

// C++ program to illustrate the
// set::key_comp() function
#include 
using namespace std;
  
int main()
{
    // creating a set named 'a'
    set a;
  
    set::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::iterator it = a.begin();
  
    // printing elements of all set
    do {
        cout << *it << " ";
    } while (comp(*(++it), l));
  
    return 0;
}
输出:
Set a has the numbers: 0 1 2 3 4 5 6 7 8 9
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”