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中所有元素的方法。

更新于:2022年12月13日

2K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.