hak*_*ata 17 c++ null iterator reference vector
我想从向量返回一个对象的引用,该对象在一个迭代器对象中.我怎样才能做到这一点?
我尝试了以下方法:
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
}
Run Code Online (Sandbox Code Playgroud)
在代码中,customerList是客户的向量,函数getId返回客户的id.
是对的*i吗?我怎么能返回0或null作为参考?
rek*_*o_t 25
return *i;是正确的,但是你不能返回0或任何其他这样的值.如果在向量中找不到Customer,请考虑抛出异常.
返回对向量中元素的引用时要小心.如果向量需要重新分配其内存并移动内容,则在向量中插入新元素可能会使引用无效.