user1091534
user1091534

Reputation: 384

C++ iterate unordered_map - compilation error

I try to iterate an unordered_map in C++, but it doesn't work.

The map.end() seems not to exist. I don't get what I am doing wrong. According to various examples and my previous work with iterators - end() should exist.

I tried to compile the example below with -std=c++11 and without :/

#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;
}

Upvotes: 0

Views: 321

Answers (2)

spiritwolfform
spiritwolfform

Reputation: 2293

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

did you mean:

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

instead?

Upvotes: 1

Steve
Steve

Reputation: 6424

You're using the wrong object to get to end().

Replace it.end() with map.end().

Upvotes: 3

Related Questions