【发布时间】:2015-11-23 13:42:49
【问题描述】:
我正在尝试使用for loop 访问存储在unorderd_map 中的值,但我一直在尝试使用循环的当前索引访问值。有什么建议或链接吗?谢谢。 [提示:我不想使用迭代器]。
我的示例代码:
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int main()
{
unordered_map<int,string>hash_table;
//filling my hash table
hash_table.insert(make_pair(1,"one"));
hash_table.insert(make_pair(2,"two"));
hash_table.insert(make_pair(3,"three"));
hash_table.insert(make_pair(4,"four"));
//now, i want to access values of my hash_table with for loop, `i` as index.
//
for (int i=0;i<hash_table.size();i++ )
{
cout<<"Value at index "<<i<<" is "<<hash_table[i].second;//I want to do something like this. I don't want to use iterator!
}
return 0;
}
【问题讨论】:
-
您不能只对
std::unordered_map(或std::map)使用普通数组索引,因为operator[]函数需要一个键而不是索引。 -
因此,您希望在
[1,4]中进行迭代。 -
也许你只想要一个
std::vector<std::pair<int,string> >
标签: c++ hashtable unordered-map