您好我的代码段如下
#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â
有没有人遇到过这个问题?
答案 0 :(得分:2)
答案 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;
}