473,671 Members | 2,163 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4109
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 "optimizati on" 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(vect or<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*********@dar rettenterprises .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.tug raz.at | ICQ #320057056 | |
|-------------------University of Technology, Graz----------------|
Jul 22 '05 #5
"Mike Darrett" <mi*********@da rrettenterprise s.com> wrote in message
news:d9******** *************** ***@posting.goo gle.com...
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_IT ER 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::b ack_inserter(an swer));

However, if he wants a C array:
int answer2[4];
SendData(answer 2); // 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 "ProcessFil e" 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(con st 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
4531
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 go to great lengths to restructure my code just to look concise and make it more manageable. When I say this, I'm also referring to the way I write my functions. It seems to me sometimes that I shouldn't have many void functions accepting...
2
2231
by: sci | last post by:
class A; void function(vector<A>* l) { .... } main(){ vector<A> aAList; function(&aAList);
5
2151
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 called function, I am using p1->find(1) which is returning a valid iterator and not going to the end. I am returning p1 from the called function. But in the calling function, find(1) is going to the end, i.e unable to find the key 1, which was...
26
2804
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 function call. #include <iostream> using namespace std; int* GetArray(); //function prototype void main()
6
2741
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 hostent *hp; int i=0,rc;
7
2402
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 value occurs in th vector. */
11
1775
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( const string& in, int charsPerLine, int lines, vector< string >& out ) { out.resize( 1 ); out = ""; int prev = 0;
7
1163
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, I can define a functions "dot" outside the class and it works exactly as I want. However, the problem is that this function is not associated with the class (like methods a method of the class).
2
1398
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... ______________________________________ template <class T, typename I>
0
8392
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8912
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8819
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8669
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7428
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6222
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5692
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4222
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4403
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.