我想迭代
map<string, int>
中的每个元素,而不知道其任何 string-int 值或键。
到目前为止我所拥有的:
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?
}
}
您可以像下面这样实现:
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;
}
尝试以下方法
for ( const auto &p : table )
{
std::cout << p.first << '\t' << p.second << std::endl;
}
同样可以使用普通的 for 循环来编写
for ( auto it = table.begin(); it != table.end(); ++it )
{
std::cout << it->first << '\t' << it->second << std::endl;
}
考虑到
std::map
的 value_type 是按以下方式定义的
typedef pair<const Key, T> value_type
因此,在我的示例中,p 是对 value_type 的 const 引用,其中 Key 是
std::string
,T 是 int
如果函数声明为
会更好void output( const map<string, int> &table );
value_type
的 map
是一个 pair
,其中包含键和值,因为它分别是 first
和 second
成员。
map<string, int>::iterator it;
for (it = symbolTable.begin(); it != symbolTable.end(); it++)
{
std::cout << it->first << ' ' << it->second << '\n';
}
或者使用 C++11,使用基于范围的:
for (auto const& p : symbolTable)
{
std::cout << p.first << ' ' << p.second << '\n';
}
由于 P0W 为每个 C++ 版本提供了完整的语法,我想通过查看您的代码来添加更多要点
const &
作为参数,以避免同一对象的额外副本。unordered_map
,因为它总是使用起来更快。请参阅此讨论这是示例代码:
#include <iostream>
#include <unordered_map>
using namespace std;
void output(const auto& table)
{
for (auto const & [k, v] : table)
{
std::cout << "Key: " << k << " Value: " << v << std::endl;
}
}
int main() {
std::unordered_map<string, int> mydata = {
{"one", 1},
{"two", 2},
{"three", 3}
};
output(mydata);
return 0;
}
正如来自莫斯科的@Vlad 所说, 考虑到
value_type
的 std::map
的定义方式如下:
typedef pair<const Key, T> value_type
这意味着如果您希望用更明确的类型说明符替换关键字
auto
,那么您可以这样做;
for ( const pair<const string, int> &p : table ) {
std::cout << p.first << '\t' << p.second << std::endl;
}
只是为了了解
auto
在这种情况下会翻译成什么。
甚至可以通过经典的
for
循环来完成。typedef std::map<int, int> Map;
Map mymap;
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
bool itexist = false;
int sizeMap = static_cast<int>(mymap.size());
auto it = mymap.begin();
for(int i = 0; i < sizeMap; i++){
std::cout << "Key: " << it->first << " Value: " << it->second << std::endl;
it++;
}
如果您只想迭代内容而不更改值 做:
for(const auto & variable_name : container_name(//here it is map name)){
cout << variable_name.first << " : " << variable_name.second << endl;
}
如果要修改地图内容,请删除
const
并保留&
(如果要直接修改容器内的内容)。如果您想使用容器值的 copy,也请删除 &
符号;之后,您可以通过在“variable_name”上使用 .first
和 .second
来访问它们。
其他方式:
map <int, string> myMap = {
{ 1,"Hello" },
{ 2,"stackOverflow" }
};
for (auto iter = cbegin(myMap); iter != cend(myMap); ++iter) {
cout << iter->second << endl;
}