在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: londoncontinent: europecountry: uk
结论在c++中,map被视为有序集合,这意味着组件按照它们的键属性的值进行排序。红黑树被用来在内存中实现map,并且所有操作的时间复杂度为对数级别。在遍历map时,我们必须使用迭代器,否则没有其他更简单的方法来访问map中的所有元素。
以上就是c++程序遍历字典的详细内容。
