473,497 Members | 2,158 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

returning a vector from a funciton

Hi,
first let me apologize before hand for not knowing this trivial issue and my
inability to find it after searching on the web for an answer to what seems
to be starightforward. I have used vectors (STL) for some time but have
never had the need to actually return one from a function. what i mean is
that does something like the code below work? (this is very artificial case
but just consider that this is imp to what i want to do and there isnt a way
around it)

vector<myClass> RetVector(){
vector<myClass> retVector;
Jul 22 '05 #1
6 2285
> I have used vectors (STL) for some time but have
never had the need to actually return one from a function. what i mean is
that does something like the code below work?
It works; I do that all the time.
vector<myClass> RetVector(){
vector<myClass> retVector;
.
/// add a few myClass objects to the vector
.
return retVector;
}

int main (){
vector<myClass> getVector;

getVector = RetVector();
The code above has default construction and assignment. You might
prefer

vector<myClass> getVector = RetVector();

which will involve just the construction of the getVector object under
many compilers. You should try it in your environment...

///use the vector to do some computation
return 1;
Returning 1 normally indicates error. EXIT_SUCCESS is a better choice
for successful return from main.
}
What i mean is that does the copy constructor do the right thing and I now
have faithfull copy of the orignal vector that i can now use to index
through and play to my hearts content?


Yes. Again though, the way you wrote it, the assignment operator is
used, not the copy constructor.

Now it all depends on the implementation of myClass (e.g. the
assignment operator, the copy constructor, etc.) As long as it's
implemented correctly, you are safe.

Ali

Jul 22 '05 #2
will it be quicker to do:

bool GetVector( vector<myClass>& v)
{
assert(v.size() == 0);
//Populate v;

return true;
}

int main()
{
vector<myClass> myVec;
if( GetVector(myVec) )
{
}
}

??
To reduce copying of data items?

Regard Mike
"Ali Cehreli" <ac******@yahoo.com> wrote in message
news:pa****************************@yahoo.com...
I have used vectors (STL) for some time but have
never had the need to actually return one from a function. what i mean is that does something like the code below work?


It works; I do that all the time.
vector<myClass> RetVector(){
vector<myClass> retVector;
.
/// add a few myClass objects to the vector
.
return retVector;
}

int main (){
vector<myClass> getVector;

getVector = RetVector();


The code above has default construction and assignment. You might
prefer

vector<myClass> getVector = RetVector();

which will involve just the construction of the getVector object under
many compilers. You should try it in your environment...

///use the vector to do some computation
return 1;


Returning 1 normally indicates error. EXIT_SUCCESS is a better choice
for successful return from main.
}
What i mean is that does the copy constructor do the right thing and I now have faithfull copy of the orignal vector that i can now use to index
through and play to my hearts content?


Yes. Again though, the way you wrote it, the assignment operator is
used, not the copy constructor.

Now it all depends on the implementation of myClass (e.g. the
assignment operator, the copy constructor, etc.) As long as it's
implemented correctly, you are safe.

Ali

Jul 22 '05 #3

"Affan Syed" wrote:
vector<myClass> RetVector()

Consider:

auto_ptr<vector<myClass> > RefVector() {
....
auto_ptr<vector<myClass> > result(new vector<myClass>());
result->reserve(expected items #);
....
return result.
}
No copying. Safe.

/Pavel
Jul 22 '05 #4
That is exactly the idea that i am trying to do now.. It clicked me as soon
as I had posted the note., and to top it it works perfectly fine.
Thanks
Affan
"Michael" <sl***********@hotmail.com> wrote in message
news:co*********@titan.btinternet.com...
will it be quicker to do:

bool GetVector( vector<myClass>& v)
{
assert(v.size() == 0);
//Populate v;

return true;
}

int main()
{
vector<myClass> myVec;
if( GetVector(myVec) )
{
}
}

??
To reduce copying of data items?

Regard Mike
"Ali Cehreli" <ac******@yahoo.com> wrote in message
news:pa****************************@yahoo.com...
> I have used vectors (STL) for some time but have
> never had the need to actually return one from a function. what i mean is > that does something like the code below work?


It works; I do that all the time.
> vector<myClass> RetVector(){
> vector<myClass> retVector;
> .
> /// add a few myClass objects to the vector
> .
> return retVector;
> }
>
> int main (){
> vector<myClass> getVector;
>
> getVector = RetVector();


The code above has default construction and assignment. You might
prefer

vector<myClass> getVector = RetVector();

which will involve just the construction of the getVector object under
many compilers. You should try it in your environment...
>
> ///use the vector to do some computation
> return 1;


Returning 1 normally indicates error. EXIT_SUCCESS is a better choice
for successful return from main.
> }
>
>
> What i mean is that does the copy constructor do the right thing and I now > have faithfull copy of the orignal vector that i can now use to index
> through and play to my hearts content?


Yes. Again though, the way you wrote it, the assignment operator is
used, not the copy constructor.

Now it all depends on the implementation of myClass (e.g. the
assignment operator, the copy constructor, etc.) As long as it's
implemented correctly, you are safe.

Ali


Jul 22 '05 #5
"Affan Syed" <as***@usc.edu> wrote in message
news:co**********@gist.usc.edu...
Hi,
first let me apologize before hand for not knowing this trivial issue and
my inability to find it after searching on the web for an answer to what
seems to be starightforward. I have used vectors (STL) for some time but
have never had the need to actually return one from a function. what i
mean is that does something like the code below work? (this is very
artificial case but just consider that this is imp to what i want to do
and there isnt a way around it)

vector<myClass> RetVector(){
vector<myClass> retVector;
.
/// add a few myClass objects to the vector
.
return retVector;
}

int main (){
vector<myClass> getVector;

getVector = RetVector();

///use the vector to do some computation
return 1;
}
What i mean is that does the copy constructor do the right thing and I now
have faithfull copy of the orignal vector that i can now use to index
through and play to my hearts content?
Thanks
Affan


Another great option: send the values to an output iterator. That still
works with a std::vector but also works with just about any other container.
e.g.

template <typename OITER>
void
function345(OITER oi)
{
*oi++ = 3;
*oi++ = 4;
*oi++ = 5;
}

The user can call it lots of ways:

std::vector<int> yadda; // or any other standard container
function345(std::back_inserter(yadda));

but also

int answer[3];
function345(answer);

Of course your function may somehow be tied directly to std::vector. If so
this isn't appropriate. But most functions which return a sequence of values
don't care how the client stores them.

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 22 '05 #6
I am rearranging the order of replies to maintain the natural flow of
conversation.
"Ali Cehreli" <ac******@yahoo.com> wrote in message
news:pa****************************@yahoo.com...
> I have used vectors (STL) for some time but have
> never had the need to actually return one from a function. what i mean
is
> that does something like the code below work?

It works; I do that all the time.

> vector<myClass> RetVector(){
> vector<myClass> retVector;
> .
> /// add a few myClass objects to the vector
> .
> return retVector;
> }
vector<myClass> getVector = RetVector();
"Michael" <sl***********@hotmail.com> wrote in message
news:co*********@titan.btinternet.com...
will it be quicker to do:

bool GetVector( vector<myClass>& v)
{
assert(v.size() == 0);
//Populate v;

return true;
}
??
To reduce copying of data items?


It might or might not be quicker. You have to test before to decide. In the
way I use it the most, it doesn't matter; because usually, the definitions
of such functions appear fully defined before their uses. (As in the example
I've given above.)

When the compiler applies RVO or NRVO (return value optimization or named
return value optimization), there is no copying involved.

"Affan Syed" <as***@usc.edu> wrote in message
news:co**********@gist.usc.edu... That is exactly the idea that i am trying to do now.. It clicked me as soon as I had posted the note., and to top it it works perfectly fine.


If it works for you, great!

The two functions do not have the same semantics though. The latter version,
the one that modifies the argument, must also document what happens if the
argument is not empty:

a) emit some type of error (e.g. assert, as suggested by Michael)
b) clear before adding new objects
c) append the new objects
d) something else

The first implementation does not have this concern. In that case, the
decision is pushed to the caller.

Ali

Jul 22 '05 #7

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

Similar topics

9
11890
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is...
18
2111
by: cppaddict | last post by:
Hi, Is it considered bad form to have the subscript operator return a const reference variable? If not, what is the proper way to do it? My question was prompted by the code below, my...
8
2076
by: Derek | last post by:
Some authors advocate returning const objects: const Point operator+(const Point&, const Point&); ^^^^^ Returning a const object prevents some bad code from compiling: Point a, b, c; (a +...
8
1735
by: Richard | last post by:
what is the syntax for returning a vector? temp is a vector return temp; ? return temp<>; ? return temp<int>; ?
10
4885
by: Allerdyce.John | last post by:
Hi, I have a class with a STL vector as it attribute. How can I create a method which just return a 'read-only' view? (i.e. the caller of the function can only read the vector, not write it)? ...
13
2284
by: Gernot Frisch | last post by:
Which method is the fastest/best: std::vector<intfoo1() { std::vector<intv; ... reutun v; } std::vector<int>& foo2()
7
2389
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...
2
1601
by: =?iso-8859-9?B?RGlu52F5IEFr5/ZyZW4=?= | last post by:
Following function void mdelr(int *ar1, int a, int b, int d ) { int i,j,tmp; int *temp; for (i=0; i<a; i++) {
5
3054
by: yogi_bear_79 | last post by:
Distant learning student. My lab is to write a function to perform the addition of large integers, with no limit to the number of digits. (Also have to do a subtraction, division, and...
0
6993
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
7162
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,...
1
6881
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7375
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...
1
4899
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...
0
3088
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...
0
1411
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
650
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
287
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.