473,386 Members | 1,763 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

a function which returns a vector

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
Jul 22 '05 #1
6 4088
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
Jul 22 '05 #2
* 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?
Jul 22 '05 #3
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
Jul 22 '05 #4
mi*********@darrettenterprises.com (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" | \|__| |
| pa****@sbox.tugraz.at | ICQ #320057056 | |
|-------------------University of Technology, Graz----------------|
Jul 22 '05 #5
"Mike Darrett" <mi*********@darrettenterprises.com> wrote in message
news:d9**************************@posting.google.c 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(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/
Jul 22 '05 #6

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
Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: wired | last post by:
Hi, I've just taught myself C++, so I haven't learnt much about style or the like from any single source, and I'm quite styleless as a result. But at the same time, I really want nice code and I...
2
by: sci | last post by:
class A; void function(vector<A>* l) { .... } main(){ vector<A> aAList; function(&aAList);
5
by: amit kumar | last post by:
I am calling a function which returns pointer to a map. The declaration of the map is map<int,vectxyz*>. vectxyz is a vector containing pointer to a class xyz. For map<int,vectxyz*>* p1 In the...
26
by: cdg | last post by:
Could anyone correct any mistakes in this example program. I am just trying to return an array back to "main" to be printed out. And I am not sure how a "pointer to an array" is returned to the...
6
by: Rahul K | last post by:
Hi I am working on Visual Studio on Windows. I have a function which return the list of all the IP Addresses of a machine: vector<char *getAllLocalIPAddress() { char localHostName; struct...
7
by: arnuld | last post by:
/* C++ Primer - 4/e * * 1st example from section 7.2.2, page 234 * returning 2 values from a function * * STATEMENT: * to find a specific value in a vector and number of times * that...
11
by: Daniel T. | last post by:
The function below does exactly what I want it to (there is a main to test it as well.) However, I'm curious about ideas of making it better. Anyone interested in critiquing it? void formatText(...
7
by: Kurda Yon | last post by:
Hi, I have a class called "vector". And I would like to define a function "dot" which would return a dot product of any two "vectors". I want to call this function as follow: dot(x,y). Well,...
2
by: .rhavin grobert | last post by:
hello;-) i have that following little template that defines some type of vector. it works with structs and i want to use it also for simple pointers. the problem is, in following function......
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.