C ++遍历地图 [英] C++ Loop through Map

查看:103
本文介绍了C ++遍历地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历map<string, int>中的每个元素,而又不知道其任何字符串整数值或键.

I want to iterate through each element in the map<string, int> without knowing any of its string-int values or keys.

到目前为止我所拥有的:

What I have so far:

void output(map<string, int> table)
{
       map<string, int>::iterator it;
       for (it = table.begin(); it != table.end(); it++)
       {
            //How do I access each element?  
       }
}

推荐答案

您可以像下面这样实现:

You can achieve this like following :

map<string, int>::iterator it;

for ( it = symbolTable.begin(); it != symbolTable.end(); it++ )
{
    std::cout << it->first  // string (key)
              << ':'
              << it->second   // string's value 
              << std::endl ;
}


使用 C ++ 11 (及更高版本)

for (auto const& x : symbolTable)
{
    std::cout << x.first  // string (key)
              << ':' 
              << x.second // string's value 
              << std::endl ;
}


使用 C ++ 17 (及更高版本)

for( auto const& [key, val] : symbolTable )
{
    std::cout << key         // string (key)
              << ':'  
              << val        // string's value
              << std::endl ;
}

这篇关于C ++遍历地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆