首页 > 解决方案 > 从指针向量中获取元素

问题描述

我有指针向量:std::vector<Customer*> customersList 现在我想获取其中一个元素并对他进行操作。我不确定我知道如何,我的猜测是:

Customer* source = restaurant.getCustomer(cust);

问题是我不知道在 c++ 中它是否会创建新对象,或者我只会得到对他的引用。有我的getter方法:

Customer* Table::getCustomer(int id) {
    for (int i = 0; i < customersList.size(); ++i) {
        if (customersList[i]->getId() == id)
            return customersList[i];
    }
    return nullptr;
}

谢谢

标签: c++c++11

解决方案


成员函数将返回指针的副本,即Customer不复制对象本身,仅复制对它的引用。修改返回Customer*值将导致指针对象(底层对象)的修改。

请注意,您还想使用<algorithm>标题,特别是std::find_if.

const auto  customer = std::find_if(customerList.begin(), customerList.end(),
    [id](const Customer* c){ return c->getId() == id; });

return customer == customerList.cend() ? nullptr : *customer;

推荐阅读