虽然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中的所有元素。