當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ map key_comp()用法及代碼示例

std::map::key_comp()是C++ STL中的內置函數,它返回容器使用的比較對象的副本。默認情況下,這是一個less對象,其返回值與運算符‘

用法:

key_compare map_name.key_comp();

參數:該函數不接受任何參數。


返回值:該函數返回容器使用的比較對象的副本。

以下示例說明了map::key_comp()方法:

示例1:

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

示例2:

// C++ program to illustrate the 
// map::key_comp() function 
  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // Creating a map named m; 
    map<char, int> m; 
  
    map<char, int>::key_compare 
        comp 
        = m.key_comp(); 
  
    // Inserting elements into map 
    m['a'] = 1; 
    m['b'] = 2; 
    m['c'] = 3; 
    m['d'] = 4; 
  
    cout << "Map has the elements\n"; 
  
    // Store key value of last element 
    char l = m.rbegin()->first; 
  
    // initializing the iterator 
    map<char, int>::iterator it = m.begin(); 
  
    // printing elements of all map 
    do { 
  
        cout << it->first 
             << " => "
             << it->second 
             << '\n'; 
    } while (comp((*it++).first, l)); 
  
    return 0; 
}
輸出:
Map has the elements
a => 1
b => 2
c => 3
d => 4


相關用法


注:本文由純淨天空篩選整理自ankit15697大神的英文原創作品 map key_comp() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。