[英]Get an element from a vector of pointers
我有指針向量: 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;
}
謝謝
成員函數將返回指針的副本,即Customer
對象本身不被復制,只有對它的引用。 修改返回的Customer*
將導致對pointee(底層對象)的修改。
請注意,您還希望使用<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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.