c++ - 我应该为指针赋值使用什么返回类型?

标签 c++ pointers vector

我有一个这样的结构:

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’

我的两个问题,

  1. 如何修复编译错误?我应该使用什么返回类型?

  2. 如果我想在第 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/

相关文章:

c - 传递结构指针的问题和 "conflicting types"错误

c++ - 帮助使用 std::locale?

r - 对向量的每 n 个元素应用函数

c++ - 手动调整窗口大小后 QGraphicsScene 宽度/高度没有改变

c - 你如何在 C 中移动数组的起始索引?

c - C 中的简单链表函数

matlab - 如何在 Matlab 中将向量转换为字符串

c++ - 从现有 cmake 应用程序导入的 Netbeans 项目无法在 Windows 上生成文件系统错误

c++ - 避免堆碎片的最佳 STL 容器

c++ - 如何在我的本地 apache 服务器上显示我的 Wt 应用程序?