Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > a function which returns a vector

Reply
Thread Tools

a function which returns a vector

 
 
Mike Darrett
Guest
Posts: n/a
 
      09-16-2004
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(;
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
 
Reply With Quote
 
 
 
 
JKop
Guest
Posts: n/a
 
      09-16-2004
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(;
> 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 **** 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 **** 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 ****
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 **** 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 ****") will only create ONE
vector, which will be "ret". "ret" will be returned from the function and
that blah object will *be* ret.

A **** 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
 
Reply With Quote
 
 
 
 
Alf P. Steinbach
Guest
Posts: n/a
 
      09-16-2004
* 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(;
> 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?
 
Reply With Quote
 
chris
Guest
Posts: n/a
 
      09-16-2004
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(;
> 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
 
Reply With Quote
 
Nicolas Pavlidis
Guest
Posts: n/a
 
      09-16-2004
http://www.velocityreviews.com/forums/(E-Mail Removed) (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(;
> 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" | \|__| |
| (E-Mail Removed) | ICQ #320057056 | |
|-------------------University of Technology, Graz----------------|
 
Reply With Quote
 
Cy Edmunds
Guest
Posts: n/a
 
      09-17-2004
"Mike Darrett" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) om...
> 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(;
> 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/


 
Reply With Quote
 
JKop
Guest
Posts: n/a
 
      09-17-2004

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 **** compiler.


-JKop
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
const vector<A> vs vector<const A> vs const vector<const A> Javier C++ 2 09-04-2007 08:46 PM
Initializing vector<vector<int> > and other vector questions... pmatos C++ 6 04-26-2007 05:39 PM
Free memory allocate by a STL vector, vector of vector, map of vector Allerdyce.John@gmail.com C++ 8 02-18-2006 12:48 AM
Method which returns vector on unknown type pocmatos@gmail.com C++ 5 11-11-2005 09:03 PM
how the vector is created, how to pass vector to webservices method apachesoap:Vector Rushikesh Joshi Perl Misc 0 07-10-2004 01:04 PM



Advertisments