我想从向量返回对象的引用,并且该对象位于迭代器对象中。我怎样才能做到这一点?
我尝试了以下方法:
Customer& CustomerDB::getCustomerById (const string& id) {
vector<Customer>::iterator i;
for (i = customerList.begin(); i != customerList.end() && !(i->getId() == id); ++i);
if (i != customerList.end())
return *i; // is this correct?
else
return 0; // getting error here, cant return 0 as reference they say
}
在代码中,customerList是客户的向量,函数getId返回客户的id。
Is the *i
正确的?我如何返回 0 或 null 作为引用?
return *i;
是正确的,但是您不能返回 0 或任何其他此类值。如果在向量中找不到 Customer,请考虑抛出异常。
返回对向量中元素的引用时也要小心。如果向量需要重新分配其内存并移动内容,则在向量中插入新元素可能会使您的引用无效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)