how do i declare a function with return type vector?

how do i declare a function that returns a vector?
Can you pass it in as a reference parameter instead?

EDIT: Sorry, just saw the other post, http://www.cplusplus.com/forum/beginner/21957/
Last edited on
yea that's what i did, but i was just wondering if you could make a function with return type vector, cause it will make my project easier.
You could, but I think we'd all suggest against it.

1
2
3
4
5
6
7
8
vector<int> ReturnVect()
{
	vector<int> myVect(10);

	myVect.push_back(5); // Do stuff...

	return myVect;
}


Repeat: This is not a good way to do it. It has performance implications involved with copying, the same as were mentioned in the other thread. In addition, you're getting a copy of the vector returned, not the original one.
I would not necessarily suggest against it.

The above is convenient in that it requires only one line of code to call:

 
vector<int> v = ReturnVect();


which lends itself well to more functional programming. For example:

 
PrintVect( ReturnVect() );


Returning the vector via reference parameter is annoying because then I have
to write two lines:

1
2
vector<int> v;
ReturnVect( v );


I would advocate using the return value of the function to return the container
unless it is proven to be a performance bottleneck.
It's more "traditional" to pass vectors and other containers by a pair of iterators to them. But returning a vector is generally fine. Of course, it will be, as sammy noted, inefficient in terms of the whole copying business. But chances are, it'll be fine for most programs.
@jsmith and tummychow: Fair call, thanks for your input. I've been doing real-time embedded programming recently, so I guess I'm always considering efficiency as a high priority.
Generally, I actually do agree with you. Just because of the copy overhead (which could be a problem in the future and almost never will be an advantage), I would advise against copying vectors. What happens if you've got some vector containing thousands of elements? (I can't imagine any such situation, but then again, I program for fun, not for corporate purposes.) But it's... livable. I'd prefer to pass by reference or iterator pair in most cases personally though.
thanks guys, its cool to know that i can do this. however i did not know that it would return a copy of a vector. i guess i'lll just be passing by ref then, since it is more efficient cause the vector i want is pretty big in size.

just a side question, so anytime i return a value from function, it returns not the value itself but a copy of the value? it is possible to return a reference to that value isn't of a copy? cause i mean u can pass by ref so returning by ref seems plausible to me.
Topic archived. No new replies allowed.