c++ - 从迭代器返回对象的引用

标签 c++ reference vector null iterator

我想从 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/

相关文章:

c++ - 使用成员字段调用可变类模板的成员方法

c++ - 如何优化 vector 的二分查找?

c++ - 协变返回类型无法识别

c++ - 初始化一个类成员引用变量,就像它是一个常规变量一样

更改 C 中结构体的引用

c++ - 创建 vector 时的默认值,C++

c++ - 将 textBox 传递给函数。 C++

c# - 将外部程序集添加到 ASP.NET MVC 项目的常用方法是什么?

c++ - 创建我的第一个 vector 时出错 [Visual studio 2013]

C++ vector 对象.erase