Although C does not have a dictionary, it has a dictionary-like structure called map. Each map entry contains two values − key and mapping value −. Each item is indexed using a key value, and mapped values are the values associated with the key. The mapped values may or may not be unique, but the keys are always unique. In this tutorial, we'll take a look at iterators and how they work with maps.
The iterator object points to an element in a series of elements. Iterators are commonly used with containers such as arrays and vectors, and have specific collections or operations that can be used to point to specific elements within a given range. The iterator points to the memory location of a specific element of the range and can be incremented or decremented to point to different elements present in the range or container. Let's see how iterators work.
<container_type> :: iterator iterator_name;
Let us give an example -
The Chinese translation of#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
This is a fairly simple process, the same as iterating over other containers.
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
In C, a map is treated as an ordered collection, which means that the components are ordered according to the value of their key attribute. Red-black trees are used to implement maps in memory, and the time complexity of all operations is logarithmic. When traversing the map, we have to use iterators, otherwise there is no other easier way to access all elements in the map.
The above is the detailed content of C++ program to traverse dictionary. For more information, please follow other related articles on the PHP Chinese website!