遍歷 C++ STL 中的對映(或無序對映)
在此我們將看到對映容器及其在 C++ 中的用法。對映被定義為關聯容器,以雜湊對映方式儲存元素。每個元素都與一個鍵和值關聯。沒有兩個對映值可以具有相同的鍵。這是 C++ 中對映容器中存在的一些基本方法。
begin(): 這將返回對映中第一個元素的迭代器。
end() − 這將返回對映中最後一個元素之後理論元素的迭代器。
size() − 這將返回對映中的元素數量。
max_size() − 這將返回對映可以容納的最大元素數量。
empty() − 這將返回對映是否為空。
範例
讓我們看看以下實現以獲得更好的理解 −
#include <bits/stdc++.h> using namespace std; int main() { int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 }; int num = sizeof(A) / sizeof(A[0]); map<int, int> my_map; for (int p = 0; p < num; p++) my_map[A[p]]++; cout <<"Item Frequency"<< endl; for (auto p : my_map) cout << p.first <<" : "<< p.second << endl; }
輸出
Item Frequency 2 : 4 3 : 1 4 : 2 5 : 1
unordered_map 是 C++ STL 中存在的另一種型別的地圖容器。這是一個關聯容器,它收集或儲存由鍵值對組合形成的元素。鍵用於唯一標識該值。在這種情況下,鍵和值都可以是任何預定義或使用者定義的型別。
範例
讓我們看看以下實現以獲得更好的理解 −
#include <bits/stdc++.h> using namespace std; int main() { int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 }; int num = sizeof(A) / sizeof(A[0]); unordered_map<int, int> my_map; for (int p = 0; p < num; p++) my_map[A[p]]++; cout <<Item Frequency"<< endl; for (auto p : my_map) cout << p.first <<" : "<< p.second << endl; }
輸出
Item Frequency 5 : 1 4 : 2 2 : 4 3 : 1
廣告