[英]What return type should I use for a pointer assignment?
我有一个这样的结构:
struct group
{
int index;
string name;
group* child;
};
我设置了一个向量来存储一些组结构。
现在,我尝试使用一个函数,通过索引从该向量中检索组成员,如下所示:
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;
}
如果您希望使用对指针的引用,还可以定义一个“未找到”组对象,该对象将由函数返回。
我会这样:
struct group
{
int index;
string name;
group* child;
group(int i):index(i),child(null){}
group(int i, const string& n, group& c):index(i), name(n), child(&c){}
// assuming index defines the uniqueness of your object class
bool operator == (const struct group& g)const {return (index == g.index);}
// an unique special instance of group struct
static struct group not_found;
};
group group::not_found(-1);
因此,您可以按照自己的方式定义函数:
group& getGroupByIndex(vector<group>* world, int i)
{
for(vector<group>::iterator it = world->begin();
it < world->end(); ++it)
{
if(it->index == i) return *it;
}
return group::not_found; // a reference to a special singleton instance of struct group
}
这样您就可以拨打电话了:
...
group& g = getGroupByIndex(world, index);
if(g == group::not_found)
{
// handle the not found case here
...
boost::optional
boost::optional<group&> get(vector<group>& world, int i)
{
for(auto & grp : world)
{
if(grp.index == i)
return boost::optional<group&>(grp);
}
return boost::none;
}
请注意,此解决方案具有O(n)
复杂度。 如果要基于index
搜索,建议使用一种结构,该结构具有对按index
排序的group
对象的引用,这将为您提供O(log n)
查找时间。
在那种情况下,我可能会持有一个shared_ptr
的向量和map<int, weak_ptr>
。 您也可以看看boost::multi_index
啊,这只是您2)
要点的一个旁注: nullptr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.