C++程式迭代字典
雖然C++沒有字典,但它有一個類似的結構,稱為map。map的每個條目包含兩個值——鍵和對映值。每個專案都使用鍵值進行索引,而對映值是與鍵關聯的值。對映值可以是唯一的,也可以不是唯一的,但鍵總是唯一的。在本教程中,我們將學習迭代器及其在map中的使用方法。
C++中的迭代器
迭代器物件指向元素範圍內的單個元素。迭代器通常與陣列和容器(如向量)一起使用,並且有一組特定的操作可以用來指向給定範圍內的特定元素。迭代器指向範圍中特定元素的記憶體位置,並且可以遞增或遞減以指向範圍或容器中存在的不同元素。讓我們看看迭代器是如何工作的。
語法
<container_type> :: iterator iterator_name;
讓我們來看一個例子:
示例
#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
這是一個相當簡單的過程,與迭代其他容器相同。
語法
map<datatype, datatype> mmap; for (auto itr = my.begin(); itr != mmap.end(); ++itr) { cout << itr->first << ": " << itr->second << endl; }
示例
#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中所有元素的方法。
廣告