
虽然C++没有字典,但它有一种类似字典的结构,称为map。每个map的条目中包含两个值−键和映射值−。每个项目都使用键值进行索引,而映射值是与键相关联的值。映射值可能是唯一的,也可能不是唯一的,但键始终是唯一的。在本教程中,我们将看一下迭代器以及它们如何与map一起工作。
在C++中的迭代器
迭代器对象指向一系列元素中的一个元素。迭代器通常与数组和向量等容器一起使用,并且具有可用于指向给定范围内的特定元素的特定集合或操作。迭代器指向范围的特定元素的内存位置,并且可以递增或递减以指向范围或容器中存在的不同元素。让我们看看迭代器是如何工作的。
语法
:: iterator iterator_name;
让我们举个例子 -
Example
的中文翻译为:示例
#include#include #include using namespace std; int main(){ //we are using a vector to demonstrate the working of an iterator vector myVec = { 10, 20, 30, 40, 50 }; // creating an iterator vector ::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
使用迭代器迭代地图
这是一个相当简单的过程,与迭代其他容器的过程相同。
立即学习“C++免费学习笔记(深入)”;
语法
mapmmap; for (auto itr = my.begin(); itr != mmap.end(); ++itr) { cout << itr->first << ": " << itr->second << endl; }
Example
的中文翻译为:示例
#include#include
输出
City: London Continent: Europe Country: UK
结论
在C++中,map被视为有序集合,这意味着组件按照它们的键属性的值进行排序。红黑树被用来在内存中实现map,并且所有操作的时间复杂度为对数级别。在遍历map时,我们必须使用迭代器,否则没有其他更简单的方法来访问map中的所有元素。











