c ++(和oop)的绝对新手。
只想通过将单个id传递给getter来询问如何从列表中返回一个对象(如果存在)。
我的代码如下:
class Customer
{
private:
unsigned int custNo;
std::string name;
std::string address;
/* .. */
}
class Store
{
private:
std::string storeName;
std::list<Customer *> customerBase;
std::list<Product *> productStock;
std::list<Sale*> sales;
public:
Store(std::string storeName); // constructor
std::string getStoreName();
Customer & getCustomer(unsigned int custId); //METHOD IN QUESTION
/*..*/
// Constructor
Customer::Customer(std::string name, std::string address)
{
//ctor
}
//
Customer & Store::getCustomer(unsigned int custId){
}
我知道这可能是一个基本问题。我仍然非常感谢你的帮助。提前谢谢!
答案 0 :(得分:1)
只想通过将单个id传递给getter来询问如何从列表中返回一个对象(如果存在)。
当您看到“如果它存在”时,您应该首先考虑指针。这是因为C ++中对象的唯一表示形式是可选的指针。必须始终存在值和引用。因此,您的函数的返回类型应为Customer*
,而不是Customer&
:
Customer* Store::getCustomer(unsigned int custId){
...
}
如果您需要id
快速检索,请使用map<int,Customer*>
或unordered_map<int,Customer*>
。您也可以使用列表来执行此操作,但搜索将是线性的(即,在最坏的情况下,您将遍历整个列表)。
说到指针,如果必须存储指向Customer
对象的指针,假设对象本身存储在其他容器中,那么最好在两个容器中使用shared_ptr<Customer>
,以简化资源管理。
答案 1 :(得分:0)
你可以这样做,但它很麻烦,因为列表没有排序,所以你必须遍历列表并检查每个结构是否匹配id。
相反,您可以将这些存储在std :: map中,并将ids作为其键...或者,如果您真的关心性能,则可以使用更好的unordered_map。
答案 2 :(得分:0)
假设您在班级getCustId()
中有Customer
个公共成员函数:
Customer & Store::getCustomer(unsigned int custId){
auto custIt = find_if(customerBase.begin(), customerBase.end(),
[custId](const Customer& c){ return c.getCustId() == custId });
return *custIt;
}