📜  C++ STL中的multimap key_comp()

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

std :: multimap :: key_comp()是C++ STL中的一个内置函数,它返回容器使用的比较对象的副本,默认情况下,这是一个less对象,其返回值与运算符'<‘相同。是一个函数指针或函数对象,它接受两个与容器元素类型相同的参数,并且如果按照定义的严格弱顺序将第一个参数认为在第二个参数之前,则返回true或否则返回false。两个键被视为等效如果key_comp自反地返回false(即,无论键作为参数传递的顺序)。

句法:

key_compare multimap_name.key_comp();

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

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

以下示例说明了multimap :: key_comp()方法:

范例1:

// C++ program to illustrate the
// multimap::key_comp() function
  
#include 
using namespace std;
  
int main()
{
  
    // Creating a multimap named m;
    multimap m;
  
    multimap::key_compare
        comp
        = m.key_comp();
  
    // Inserting elements into multimap
    m.insert(make_pair('a', 10));
    m.insert(make_pair('b', 20));
    m.insert(make_pair('c', 30));
    m.insert(make_pair('d', 40));
  
    cout << "Multimap has the elements\n";
  
    // Store key value of last element
    char l = m.rbegin()->first;
  
    // initializing the iterator
    map::iterator it = m.begin();
  
    // printing elements of all multimap
    do {
  
        cout << it->first
             << " => "
             << it->second
             << '\n';
  
    } while (comp((*it++).first, l));
  
    return 0;
}
输出:
Multimap has the elements
a => 10
b => 20
c => 30
d => 40

范例2:

// C++ program to illustrate the
// multimap::key_comp() function
  
#include 
using namespace std;
  
int main()
{
  
    // Creating a multimap named m;
    multimap m;
  
    multimap::key_compare
        comp
        = m.key_comp();
  
    // Inserting elements into multimap
    m.insert(make_pair('a', 100));
    m.insert(make_pair('b', 200));
    m.insert(make_pair('c', 300));
    m.insert(make_pair('d', 400));
  
    cout << "Multimap has the elements\n";
  
    // Store key value of last element
    char l = m.rbegin()->first;
  
    // initializing the iterator
    map::iterator it = m.begin();
  
    // printing elements of all multimap
    do {
  
        cout << it->first
             << " => "
             << it->second
             << '\n';
  
    } while (comp((*it++).first, l));
  
    return 0;
}
输出:
Multimap has the elements
a => 100
b => 200
c => 300
d => 400
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”