a function which returns a vector

Discussion in 'C++' started by Mike Darrett, Sep 16, 2004.

  1. Mike Darrett

    Mike Darrett Guest

    Hello,

    First off, I'm a C++ newbie, so please turn your flame guns off. ;)

    I'm wondering if this is the correct way to have a function return a
    vector:

    vector<int> GetVecData()
    {
    vector<int> ret;

    ret.push_back(2); // enter data
    ret.push_back(5);
    ret.push_back(8);
    ret.push_back(3);

    return ret;
    }


    Can anyone tell me what exactly is happening in the above code? (Are
    the vector data points copied? Or is something else happening?)

    I'm guessing (hoping) it isn't doing something like the following:

    int *GetArrayData()
    {
    int data[10];

    data[0] = 2; // enter data
    data[1] = 5;
    data[2] = 8;
    data[3] = 3;
    return &data[0];
    }

    The above code should fail, since the data array is destroyed once the
    function finishes. (Right?)


    Thanks!

    Mike Darrett
    Mike Darrett, Sep 16, 2004
    #1
    1. Advertising

  2. Mike Darrett

    JKop Guest

    Mike Darrett posted:

    > Hello,
    >
    > First off, I'm a C++ newbie, so please turn your flame guns off. ;)
    >
    > I'm wondering if this is the correct way to have a function return a
    > vector:


    Well, it's *one* way!

    > vector<int> GetVecData()
    > {
    > vector<int> ret;
    >
    > ret.push_back(2); // enter data
    > ret.push_back(5);
    > ret.push_back(8);
    > ret.push_back(3);
    >
    > return ret;
    > }
    >
    >
    > Can anyone tell me what exactly is happening in the above code?


    Some-one calls your function.
    The object "ret" is created.
    You do "push_back" on it 4 times.

    Now here's the sticky part:

    You return a vector object by value. What happens? well...

    Scenario 1: No optimization, or what I like to call "a shit compiler":

    The return statement is reached.
    A new name-less object is created, copy-constructed from "ret".
    "ret" is destroyed.
    This new name-less object is returned to the calling function.

    Scenario 2: Optimization, (it shouldn't be called "optimization" in this
    case - if a compiler doesn't do this then it isn't just simply a "non-
    optimizing" compiler, it's a pesimizing shit compiler):

    The return statement is reached.
    "ret" is returned to the calling function.


    Okay, now moving on...

    What can you do with the returned object?

    A) Bind it to a const reference:

    vector const& blah = GetVec();

    Downside: The object is const.
    Upside: You're guaranteed that no copy is made, even with a shit
    compiler.

    B) Copy-construct an object from it:

    vector blah( GetVec() );
    //or
    vector blah = GetVec();

    Upside: The object is non-const, it's yours to keep!

    Downside: A shit compiler will actually make a copy of the returned
    object, instead of just hanging on to it.


    Overall, if you do the following:

    vector blah = GetVec();

    An average compiler (by which I mean "not shit") will only create ONE
    vector, which will be "ret". "ret" will be returned from the function and
    that blah object will *be* ret.

    A shit compiler could create 3 objects: "ret", the object returned from the
    function, the blah object.


    NOTE: Even though some people may refer to the compiler which creates only
    one vector as an "optimizing" compiler, don't be fooled! There's nothing
    "optimizing" about it - that's the bog standard, just like a 10 year old
    should be able to tie their shoe laces.

    A compiler that makes 2 or 3 objects in the above is tantamount to a 10 year
    old unable to tie their shoe laces.


    Hope that helps.


    > int *GetArrayData()
    > {
    > int data[10];
    >
    > data[0] = 2; // enter data
    > data[1] = 5;
    > data[2] = 8;
    > data[3] = 3;
    > return &data[0];
    > }
    >
    > The above code should fail, since the data array is destroyed once the
    > function finishes. (Right?)



    Absolutely correct. It looks like you already know this, but just in case
    you don't, note that you can't pass an array as an argument to a function,
    nor can you return one from a function. You can try all right! but all it
    will get is a pointer to the array (which may be about to be destroyed, as
    in your above example).


    -JKop
    JKop, Sep 16, 2004
    #2
    1. Advertising

  3. * Mike Darrett:
    > Hello,
    >
    > First off, I'm a C++ newbie, so please turn your flame guns off. ;)
    >
    > I'm wondering if this is the correct way to have a function return a
    > vector:
    >
    > vector<int> GetVecData()
    > {
    > vector<int> ret;
    >
    > ret.push_back(2); // enter data
    > ret.push_back(5);
    > ret.push_back(8);
    > ret.push_back(3);
    >
    > return ret;
    > }
    >
    >
    > Can anyone tell me what exactly is happening in the above code? (Are
    > the vector data points copied? Or is something else happening?)


    The standard specifies that the above code should work _as if_ the
    vector is copied.

    So it's perfectly safe.

    Your compiler may optimize it a bit, e.g. the compiler may translate
    it to something like


    vector<int>& GetVecData( vector<int>& ret )
    {
    ret.push_back( 2 );
    ...
    return ret;
    }


    to avoid unnecessary copying while preserving the effect; this is called
    a Return Value Optmization (RVO), and whether it's performed depends
    entirely on the compiler and on the options specified to the compiler.




    > I'm guessing (hoping) it isn't doing something like the following:
    >
    > int *GetArrayData()
    > {
    > int data[10];
    >
    > data[0] = 2; // enter data
    > data[1] = 5;
    > data[2] = 8;
    > data[3] = 3;
    > return &data[0];
    > }


    No.


    > The above code should fail, since the data array is destroyed once the
    > function finishes. (Right?)


    Yes.



    > Thanks!


    You're welcome.

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, Sep 16, 2004
    #3
  4. Mike Darrett

    chris Guest

    Mike Darrett wrote:

    > Hello,
    >
    > First off, I'm a C++ newbie, so please turn your flame guns off. ;)


    Never! BWAHAHAHAHA

    > I'm wondering if this is the correct way to have a function return a
    > vector:
    >
    > vector<int> GetVecData()
    > {
    > vector<int> ret;
    >
    > ret.push_back(2); // enter data
    > ret.push_back(5);
    > ret.push_back(8);
    > ret.push_back(3);
    >
    > return ret;
    > }


    Yep, that is fine and dandy. Unfortunatly the entire vector will (almost
    certainly) get copied during the return, but at least at first that kind
    of thing shouldn't bother you.

    You could avoid that by writing something like:

    vector<int>* GetVecData() {
    vector<int>* ret=new vector<int>;
    ....
    return ret;
    }

    However of course, then you'll have to remember to delete it later.

    or

    void GetVecData(vector<int> & in) {
    ....
    }

    and get passed a vector "in".

    However unless this is a critical path of your code, the vectors are
    REALLY big, or you need every bit of speed, I would personally just use
    what you had originally. It's correct and it's the easiest way to go
    about things :)

    An alternative would be to use so called "smart pointers". Unfortunatly
    I don't really know much about these (I really should). You can either
    go look them up, or wait for someone to post about them :)

    Chris
    chris, Sep 16, 2004
    #4
  5. (Mike Darrett) writes:

    > Hello,
    >
    > First off, I'm a C++ newbie, so please turn your flame guns off. ;)


    :)

    > I'm wondering if this is the correct way to have a function return a
    > vector:


    There where many answers given here my two cents:

    > vector<int> GetVecData()
    > {
    > vector<int> ret;
    >
    > ret.push_back(2); // enter data
    > ret.push_back(5);
    > ret.push_back(8);
    > ret.push_back(3);
    >
    > return ret;
    > }


    By returning the vector and all it's elements are copied, which means
    that the copy consttrucor will be called for the vector and each of its
    elements (if they would be objects there would be one for the elements
    :) )

    > I'm guessing (hoping) it isn't doing something like the following:
    >
    > int *GetArrayData()
    > {
    > int data[10];
    >
    > data[0] = 2; // enter data
    > data[1] = 5;
    > data[2] = 8;
    > data[3] = 3;
    > return &data[0];
    > }


    > The above code should fail, since the data array is destroyed once the
    > function finishes. (Right?)


    Yeah, you're right, with a little dirty trick you can make it working,
    by setting the array static, but thats very dirty :).

    Kind regrads,Nicolas

    --
    | Nicolas Pavlidis | Elvis Presly: |\ |__ |
    | Student of SE & KM | "Into the goto" | \|__| |
    | | ICQ #320057056 | |
    |-------------------University of Technology, Graz----------------|
    Nicolas Pavlidis, Sep 16, 2004
    #5
  6. Mike Darrett

    Cy Edmunds Guest

    "Mike Darrett" <> wrote in message
    news:...
    > Hello,
    >
    > First off, I'm a C++ newbie, so please turn your flame guns off. ;)
    >
    > I'm wondering if this is the correct way to have a function return a
    > vector:
    >
    > vector<int> GetVecData()
    > {
    > vector<int> ret;
    >
    > ret.push_back(2); // enter data
    > ret.push_back(5);
    > ret.push_back(8);
    > ret.push_back(3);
    >
    > return ret;
    > }
    >
    >
    > Can anyone tell me what exactly is happening in the above code? (Are
    > the vector data points copied? Or is something else happening?)
    >
    > I'm guessing (hoping) it isn't doing something like the following:
    >
    > int *GetArrayData()
    > {
    > int data[10];
    >
    > data[0] = 2; // enter data
    > data[1] = 5;
    > data[2] = 8;
    > data[3] = 3;
    > return &data[0];
    > }
    >
    > The above code should fail, since the data array is destroyed once the
    > function finishes. (Right?)
    >
    >
    > Thanks!
    >
    > Mike Darrett


    As the others have said, you can return a std::vector just like any other
    object. However, when I have a function which returns a sequence of values I
    usually write it as follows:

    template <typename OUT_ITER>
    void SendData(OUT_ITER oi)
    {
    *oi++ = 2;
    *oi++ = 5;
    *oi++ = 8;
    *oi++ = 3;
    }

    Now if the client wants a std::vector for output he can call this as
    follows:

    std::vector<int> answer;
    answer.reserve(4); // optional -- may be a little faster
    SendData(std::back_inserter(answer));

    However, if he wants a C array:
    int answer2[4];
    SendData(answer2); // dangerous in general -- prone to overflow errors

    There are lots of other options (list, deque, output stream, etc.) for
    output iterators. For most of my functions I don't care how the client
    stores the output data, so why make him do it my way?

    --
    Cy
    http://home.rochester.rr.com/cyhome/
    Cy Edmunds, Sep 17, 2004
    #6
  7. Mike Darrett

    JKop Guest

    Just to give a little example:

    I'm currenting writing a Win32 program that'll deal with
    renaming certain files. I have a loop that goes through the
    files and then I have a function called "ProcessFile" that
    will decide whether the file should be renamed, and if so,
    what it's new name should be. So what I need is to return
    two things from the function, a bool, and an std::string.

    Here's what I did:

    struct BoolAndString
    {
    bool proceed;
    std::string str;
    };

    BoolAndString ProcessFile(const char* const old_name);

    The calling function, once it receives this new filename,
    doesn't have to change it at all, so a const object will
    suffice, that's why I do:

    BoolAndString const& blah = ProcessFile(...

    If I'd needed a non-const object, I would've done:

    BoolAndString blah = ProcessFile(...

    Which shouldn't be any less efficent... unless ofcourse
    you're dealing with a shit compiler.


    -JKop
    JKop, Sep 17, 2004
    #7
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. pmatos
    Replies:
    6
    Views:
    23,778
  2. Replies:
    5
    Views:
    398
    Eric Pruneau
    Nov 11, 2005
  3. Replies:
    8
    Views:
    1,913
    Csaba
    Feb 18, 2006
  4. Javier
    Replies:
    2
    Views:
    558
    James Kanze
    Sep 4, 2007
  5. Rushikesh Joshi
    Replies:
    0
    Views:
    356
    Rushikesh Joshi
    Jul 10, 2004
Loading...

Share This Page