首頁  >  文章  >  後端開發  >  C++程式遍歷字典

C++程式遍歷字典

王林
王林轉載
2023-09-01 11:13:061558瀏覽

C++程式遍歷字典

雖然C 沒有字典,但它有一種類似字典的結構,稱為map。每個map的條目中包含兩個值鍵和映射值。每個項目都使用鍵值進行索引,而映射值是與鍵相關聯的值。映射值可能是唯一的,也可能不是唯一的,但鍵始終是唯一的。在本教程中,我們將看一下迭代器以及它們如何與map一起工作。

在C 中的迭代器

迭代器物件指向一系列元素中的一個元素。迭代器通常與數組和向量等容器一起使用,並且具有可用於指向給定範圍內的特定元素的特定集合或操作。迭代器指向範圍的特定元素的記憶體位置,並且可以遞增或遞減以指向範圍或容器中存在的不同元素。讓我們看看迭代器是如何運作的。

文法

<container_type> :: iterator iterator_name;

讓我們舉個例子 -

Example

的中文翻譯為:

範例

#include <iostream>
#include <iterator>
#include <vector>

using namespace std;

int main(){
   //we are using a vector to demonstrate the working of an iterator
   vector<int> myVec = { 10, 20, 30, 40, 50 };
     
   // creating an iterator
   vector<int>::iterator it;
     
   // iterating through the elements
   cout << "The elements are: ";
   //the begin and end are used to define the range
   for (it = myVec.begin(); it < myVec.end(); it++)
      cout << *it << " ";
     
   return 0;   
}

輸出

The elements are: 10 20 30 40 50

使用迭代器迭代地圖

這是一個相當簡單的過程,與迭代其他容器的過程相同。

文法

map<datatype, datatype> mmap;
for (auto itr = my.begin(); itr != mmap.end(); ++itr) {
   cout << itr->first << ": " << itr->second << endl;
}

Example

的中文翻譯為:

範例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <string, string> mmap = {{"City", "London"}, {"Country", "UK"}, {"Continent", "Europe"}};

   //iterating through the contents
   for (auto itr = mmap.begin(); itr != mmap.end(); ++itr) {
      cout << itr->first << ": " << itr->second << endl;
   }
   return 0;
}

輸出

City: London
Continent: Europe
Country: UK

結論

在C 中,map被視為有序集合,這意味著組件按照它們的鍵屬性的值進行排序。紅黑樹被用來在記憶體中實現map,並且所有操作的時間複雜度為對數等級。在遍歷map時,我們必須使用迭代器,否則沒有其他更簡單的方法來存取map中的所有元素。

以上是C++程式遍歷字典的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除