c++ - 从指针向量中获取元素
问题描述
我有指针向量: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*
值将导致指针对象(底层对象)的修改。
请注意,您还想使用<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;
推荐阅读
- asp.net-core-2.0 - Kestrel 在哪里寻找要监听的端口?
- node.js - 带有 nginx 配置的 socket.io
- vue.js - Vue JS表格标签中如何正确使用v-if和v-else
- php - 我有多个与数组同名且值相同的单选按钮
- symfony - Symfony4 安全中的两种认证方式
- php - 在 wordpress 中找不到函数“remove_comment_support”或函数名无效
- mongodb - 分片的 mongodb 集群只使用一个分片
- azure - 将 Sparkfun ESP8266 Thing 连接到 Azure IoT Hub
- elasticsearch - Elasticsearch:在匹配查询中应用恒定分数,但在分析搜索词之后?
- jquery - 如何在选择选择器搜索输入中添加占位符