for(auto& x:unordered_map变量) - 此语句抛出错误

时间:2013-12-20 21:07:42

标签: c++ c++11

您好我的代码段如下

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

在linux上编译时会抛出错误:

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â

有没有人遇到过这个问题?

2 个答案:

答案 0 :(得分:2)

您正在使用的编译器版本(gcc 4.3)不支持自动变量。

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

自动键入的变量N1984否

答案 1 :(得分:0)

value_type的{​​{1}}是一对键和值,您需要选择第二个。

unordered_map

此外,您可能希望通过引用传递以避免复制并导致悬空点。

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