Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ How to return a vector by reference?

I'm a c++ student and could use some help with understanding and doing this part of my assignment.

I have a vector of SalesItem objects:

class Invoice
{
public:
    //blabla
    vector<SalesItem> *getSalesItems(); //code provided by the assignment.
private:
{
    //blabla
    vector<SalesItem> salesItems;
};

and I need to return that vector as a reference:

void Invoice::getSalesItems() //error on this line. Code provided by assignment.
{
    return salesItems; //error on this line.
}

Now, I know that the things that are giving me errors are obviously wrong, I don't even have any pointers or references in there. I'm posting those few lines of code just as an example of what I would like to see (or more realistically, what makes sense to me.)

I want a get function that works like other get functions for types like int or string, except this one has to return by reference (as required by the assignment.)

Unfortunately, my understanding of vectors and references is not up to merit for this problem, and I do not have any educational resources that can help me on this. If someone could please help me understand what to do, I would greatly appreciate it.

Any extra information will be gladly given.

like image 712
Crazierinzane Avatar asked Apr 23 '14 01:04

Crazierinzane


1 Answers

You need to specify the return type. Moreover, it is better to provide both const and non-const versions. Code as follows:

class Invoice
{
public:
          vector<SalesItem> &getSalesItems()       { return salesItems; }
    const vector<SalesItem> &getSalesItems() const { return salesItems; }
private:
    vector<SalesItem> salesItems;
};

Sample usage:

Invoice invoice;
vector<SalesItem> &saleItems = invoice.getSalesItems(); // call the first (non-const) version
const Invoice &const_invoice = invoice;
const vector<SalesItem> &saleItems = const_invoice.getSalesItems(); // call the second (const) version
like image 80
Danqi Wang Avatar answered Oct 06 '22 01:10

Danqi Wang