對映 key_comp() 函式於 C++ STL 中
本文將探討 C++ STL 中 map::key_comp() 函式的工作原理、語法和示例。
什麼是 C++ STL 中的 Map?
Map 是關聯容器,便於儲存由鍵值和按特定順序對映的值組合而成的元素。在 Map 容器中,使用關聯鍵始終對資料進行內部排序。Map 容器中的值透過其唯一鍵進行訪問。
什麼是 map::key_comp()?
map::key_comp( ) 是 <map> 標頭檔案中的一項函式。此函式返回鍵比較物件的副本。這在預設情況下是小於等於物件,其作用類似於小於運算子 <。該物件檢查 Map 容器中元素鍵的順序。此函式接受兩個引數並檢查其金鑰,如果第一個元素較小且應該排在第二個元素之前,則返回 true,否則將返回 false。
語法
Key_compare.key_comp();
引數
此函式不接受任何引數。
返回值
它返回一個比較物件。
示例
輸入
map<char, int> newmap; map<char, int> :: key_compare cmp = newmap.key_comp(); newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3;
輸出
a = 1 b = 2 c = 3
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, char> TP;
map<int, char>::key_compare cmp = TP.key_comp();
// Inserting elements
TP[0] = 'a';
TP[1] = 'b';
TP[2] = 'c';
TP[3] = 'd';
cout<<"Elements in the map are : \n";
int val = TP.rbegin()->first;
map<int, char>::iterator i = TP.begin();
do {
cout << i->first << " : " << i->second<<'\n';
} while (cmp((*i++).first, val));
return 0;
}輸出
Elements in the map are: 0 : a 1 : b 2 : c 3 : d
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char, int> TP;
map<char, int>::key_compare cmp = TP.key_comp();
// Inserting elements
TP['a'] = 0;
TP['b'] = 1;
TP['c'] = 3;
TP['d'] = 2;
cout<<"Elements in the map are : \n";
char val = TP.rbegin()->first;
map<char, int>::iterator i = TP.begin();
do {
cout << i->first << " : " << i->second<<'\n';
} while (cmp((*i++).first, val));
return 0;
}輸出
Elements in the map are: a : 0 b : 1 c : 3 d : 2
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP