我想从 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
}
代码中customerList是一个客户 vector ,getId函数返回客户的id。
*i
是否正确?以及如何返回 0 或 null 作为引用?
最佳答案
return *i;
是正确的,但是您不能返回 0 或任何其他此类值。如果在 vector 中找不到客户,请考虑抛出异常。
返回对 vector 中元素的引用时也要小心。如果 vector 需要重新分配其内存并移动内容,则在 vector 中插入新元素会使您的引用无效。
关于c++ - 从迭代器返回对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10550011/