AI编程助手
AI免费问答

C++程序打印字典

PHPz   2023-09-11 10:33   1306浏览 转载

c++程序打印字典

映射是 C++ 中的一种特殊类型的容器,其中每个元素都是一对两个值,即键值和映射值。键值用于索引每个项目,映射值是与键关联的值。无论映射值是否唯一,键始终是唯一的。要在 C++ 中打印映射元素,我们必须使用迭代器。一组项目中的一个元素由迭代器对象指示。迭代器主要与数组和其他类型的容器(例如向量)一起使用,并且它们具有一组特定的操作,可用于识别特定范围内的特定元素。可以增加或减少迭代器来引用范围或容器中存在的不同元素。迭代器指向范围内特定元素的内存位置。

使用迭代器在 C++ 中打印地图

首先,我们看一下如何定义迭代器来打印地图的语法。

语法

map<datatype datatype> myMap;
map<datatype datatype> :: iterator it;
for (it = myMap.begin(); it first second 
<p>替代方法是这样的 -</p>
<pre class="brush:php;toolbar:false;">map<datatype datatype> mmap;
for (auto itr = my.begin(); itr != mmap.end(); ++itr) {
   cout first second 
<p>让我们举一个使用这两种方法的例子 -</p>
<h3>示例</h3>
<pre class="brush:cpp;toolbar:false;">#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <string string> mmap = {{"City", "Berlin"}, {"Country", "Germany"}, {"Continent", "Europe"}};
   map <string string>::iterator itr;

   //iterating through the contents
   for (itr = mmap.begin(); itr != mmap.end(); ++itr) {
      cout first second 
<h3>输出</h3>
<pre class="brush:php;toolbar:false;">City: Berlin
Continent: Europe
Country: Germany

使用第二种方法 -

示例

#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 first second 
<h3>输出</h3>
<pre class="brush:php;toolbar:false;">City: London
Continent: Europe
Country: UK

结论

要在 C++ 中显示映射的内容,我们必须使用迭代器,否则很难打印出值。使用迭代器可以很容易地遍历映射中的所有条目并显示它们的值。

C++免费学习笔记(深入):立即学习
>在学习笔记中,你将探索 C++ 的入门与实战技巧!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除