C++迭代unordered_map - 编译错误

C++ iterate unordered_map - compilation error

本文关键字:编译 错误 map 迭代 unordered C++      更新时间:2023-10-16

我尝试在C++中迭代unordered_map,但它不起作用。

map.end() 似乎不存在。我不明白我做错了什么。根据各种示例和我之前使用迭代器的工作 - end() 应该存在。

我尝试使用 -std=c++11 编译下面的示例,但没有 :/

#include <unordered_map>
#include <iostream>
#include <vector>
int main(int argc, char** argv){
    std::unordered_map<std::string, unsigned long> map;
    std::vector<std::string> keys;
    std::unordered_map<std::string, unsigned long>::iterator it;
    for (it=map.begin(); it != it.end(); ++it){
        keys.push_back(it->first);
    }
    for (unsigned long i=0; i < keys.size();i++){
        std::cout<<keys[i];
    }
  return 0;
}

您使用了错误的对象来访问end()

it.end()替换为 map.end()

for (it=map.begin(); it != it.end(); ++it){
//                        ^^^^  the error is here

你的意思是:

for (it=map.begin(); it != map.end(); ++it){    // correct

相反?