问题描述
我想从向量返回对象的引用,并且该对象位于迭代器对象中。我怎么能这样做?
I want to return a reference of an object from a vector, and the object is in an iterator object. How can I do that?
我尝试了以下内容:
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。
In the code, customerList is a vector of customers, and the function getId returns the id of the customer.
是 * i
对吗?如何返回0或null作为参考?
Is the *i
correct? And how can I return 0 or null as a reference?
推荐答案
return * i;
是正确的,但是你不能返回0或任何其他这样的值。如果在向量中找不到Customer,请考虑抛出异常。
return *i;
is correct, however you can't return 0, or any other such value. Consider throwing an exception if the Customer is not found in the vector.
在向量中返回对元素的引用时也要小心。如果向量需要重新分配其内存并移动内容,则在向量中插入新元素可能会使引用无效。
Also be careful when returning references to elements in vector. Inserting new elements in vector can invalidate your reference if vector needs to re-allocate its memory and move the contents.
这篇关于从迭代器返回对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!