从迭代器返回对象的引用

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,请考虑抛出异常.

返回对向量中元素的引用时要小心.如果向量需要重新分配其内存并移动内容,则在向量中插入新元素可能会使引用无效.

  • 如果您知道向量将包含的最大元素数,则可以使用向量的"reserve()"函数预先保留容量.然后,只要向量的大小不超过容量,插入新元素时就不会移动元素.如果您事先不知道容量,请考虑使用其他类型的容器.例如,`std :: deque`的行为与vector类似,但在需要调整大小时不会重新分配所有内存; 它只是为新元素分配一个新块(因此内存部分被分段). (2认同)