Sandeep Thota
Sandeep Thota

Reputation: 145

for(auto& x : unordered_map variable) - this statement throwing error

Hi my code snippet is as below

#include <iostream>
#include <string>
#include <unordered_map>

struct job
{
    int priority;
    int state;
    std::string name;
};
job* selectJob(std::unordered_map<int, job*> jobList)
{
    for (auto& x : jobList)
    {
        if(x->state == 1)
        return x;
    }
    return NULL;
}

int main()
{
    std::unordered_map<int, job*> jobList;
    job a = { 1, 1, "a" };
    jobList.insert(std::make_pair<int, job*>(1, &a));
    job *selected = NULL;

    while (NULL != (selected = selectJob(jobList)))
    {
        std::cout << "Name: " << selected->name << "Prio: " << selected->priority << std::endl;
        selected->state = 2;
    }
    return 0;
}

When compiled on linux it is throwing an error:

g++ -std=gnu++0x q.cpp
q.cpp: In function âjob* selectJob(std::unordered_map<int, job*, std::hash<int>, std::equal_to<int>, std::allocator<std::pair<const int, job*> > >&)â:
q.cpp:13: error: a function-definition is not allowed here before â:â token
q.cpp:18: error: expected primary-expression before âreturnâ
q.cpp:18: error: expected `;' before âreturnâ
q.cpp:18: error: expected primary-expression before âreturnâ
q.cpp:18: error: expected `)' before âreturnâ

Has anyone faced this issue?

Upvotes: 0

Views: 562

Answers (2)

user3458
user3458

Reputation:

The compiler version you're using (gcc 4.3) does not support auto variables.

http://gcc.gnu.org/gcc-4.3/cxx0x_status.html

auto-typed variables N1984 No

Upvotes: 2

111111
111111

Reputation: 16148

the value_type of an unordered_map is a pair of the key and value, you need to select the second.

job* selectJob(std::unordered_map<int, job*> jobList)
{
    for (auto& x : jobList)
    {
        if(x->second->state == 1)
        return x->second;
    }
    return NULL;
}

Also you might want to pass by reference to avoid copying and leading to a dangling point.

job* selectJob(std::unordered_map<int, job*>& jobList)

Upvotes: 0

Related Questions