简体   繁体   中英

c++ returning object from function?

Absolute newbie to c++ (and oop) as well.

Just wanted to ask how to return an object from a list (if it exists), by passing a single id to a getter.

My code is as follows:

    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){


    }   

I know this might be a farily basic question. Still I would very much appreciate the help. Thanks in advance!

Just wanted to ask how to return an object from a list (if it exists), by passing a single id to a getter.

Pointer is the first thing that you should think when you see "if it exists". This is because the only representation of an object in C++ that can be optional is a pointer. Values and references must always be present. Therefore, the return type of your function should be Customer* , not Customer& :

Customer* Store::getCustomer(unsigned int custId){
    ...
}

If you need fast retrieval by an id , use a map<int,Customer*> or unordered_map<int,Customer*> . You could do it with a list, too, but the search would be linear (ie you would go through the entire list in the worst case).

Speaking of pointers, if you must store pointers to Customer objects, assuming that the objects themselves are stored in some other container, you may be better off using shared_ptr<Customer> in both containers, to simplify resource management.

You can do this but it would be cumbersome as list is not sorted so you have to traverse the list and check each structure for matching id.

Rather you could store these in std::map with ids as their keys...OR much better unordered_map if you really care about performance.

Assuming you have getCustId() public member function in class 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM