我有一个这样的结构:
struct group
{
int index;
string name;
group* child;
};
然后我设置了一个 vector 来存储一些组结构。
现在我正在尝试使用一个函数来按索引从该 vector 中检索组成员,如下所示:
148 newGroup.child = getGroupByIndex(world, i);
函数的定义是:
group& getGroupByIndex(vector<group>* world, int i)
{
for(vector<group>::iterator it = world->begin();
it < world->end(); ++it)
{
if(it->index == i) return *it;
}
267 return 0;
}
不幸的是,它甚至无法编译。
错误信息是:
tree.cpp: In function ‘int main()’:
tree.cpp:148: error: cannot convert ‘group’ to ‘group*’ in assignment
tree.cpp: In function ‘group& getGroupByIndex(std::vector<group, std::allocator<group> >*, int)’:
tree.cpp:267: error: invalid initialization of non-const reference of type ‘group&’ from a temporary of type ‘int’
我的两个问题,
如何修复编译错误?我应该使用什么返回类型?
如果我想在第 267 行返回一个空指针,我应该使用什么?我尝试了 (void *)0 和 0,但都不起作用。
最佳答案
我觉得应该是这样的:
group* getGroupByIndex(vector<group*> world, int i) // See position of two *
{
for(vector<group*>::iterator it = world.begin();
it < world.end(); ++it)
{
if(it->index == i)
return *it;
}
return 0;
}
或
group* getGroupByIndex(vector<group> *world, int i) // See position of two *
{
for(vector<group>::iterator it = world->begin();
it < world->end(); ++it)
{
if(it->index == i)
return &(*it);
}
return 0;
}
关于c++ - 我应该为指针赋值使用什么返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15195601/