NoN*_*ame 171 c++ dictionary
我想在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?
}
}
Run Code Online (Sandbox Code Playgroud)
P0W*_*P0W 390
您可以像下面这样实现:
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 ;
}
Run Code Online (Sandbox Code Playgroud)
使用C++ 11 (及以后),
for (auto const& x : symbolTable)
{
std::cout << x.first // string (key)
<< ':'
<< x.second // string's value
<< std::endl ;
}
Run Code Online (Sandbox Code Playgroud)
使用C++ 17 (及以后),
for( auto const& [key, val] : symbolTable )
{
std::cout << key // string (key)
<< ':'
<< val // string's value
<< std::endl ;
}
Run Code Online (Sandbox Code Playgroud)
Vla*_*cow 26
请尝试以下方法
for ( const auto &p : table )
{
std::cout << p.first << '\t' << p.second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
可以使用普通的for循环编写相同的内容
for ( auto it = table.begin(); it != table.end(); ++it )
{
std::cout << it->first << '\t' << it->second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
考虑到value_type for std::map
是按以下方式定义的
typedef pair<const Key, T> value_type
Run Code Online (Sandbox Code Playgroud)
因此在我的例子中,p是对value_type的const引用,其中Key是std::string
和T是int
如果将函数声明为更好的话也会更好
void output( const map<string, int> &table );
Run Code Online (Sandbox Code Playgroud)
Col*_*mbo 14
所述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';
}
Run Code Online (Sandbox Code Playgroud)
或者使用C++ 11,使用基于范围的:
for (auto const& p : symbolTable)
{
std::cout << p.first << ' ' << p.second << '\n';
}
Run Code Online (Sandbox Code Playgroud)
正如来自莫斯科的@Vlad 所说,考虑到value_type
forstd::map
定义如下:
typedef pair<const Key, T> value_type
Run Code Online (Sandbox Code Playgroud)
这意味着如果您希望auto
用更明确的类型说明符替换关键字,那么您可以这样做;
for ( const pair<const string, int> &p : table ) {
std::cout << p.first << '\t' << p.second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
只是为了理解auto
在这种情况下会转化为什么。
由于 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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
272784 次 |
最近记录: |