Within a function a vector could be given back via "return".
Example:

vector<int>myvector()
{
 vector<int>myvector;
 return myvector;
}

Better would be to work with a reference, e.g.:

vector<int>(&myvector)()
{
 vector<int>myvector;
}

But this reference doesn't work. Does anyone have an idea what the correct code would be?

Edited 5 Years Ago by Sunshine2011: n/a

describe your problem in more detail, anyway if i got it right, you can't do what you want cuz the compiler won't let you return a reference to temporary object(declared in the function body)

ps: your code isn't even valid so i can't tell exactlty what you really want..

Edited 5 Years Ago by dospy: n/a

Ok. I think it is the best is to post the code for a better understanding.

#include <iostream>
#include <vector>

using namespace std;

//function for creating the vector, it returns the vector.
vector<int>VectorCreate();
vector<int>VectorCreate()
{
  vector<int> myvector;
  return myvector;
}

//saving a element in the vector and shows it on the monitor
void test(vector<int>myvector,int &a);
void test(vector<int>myvector,int &a)
{
  myvector.push_back(a);
  cout<<myvector[0];
}

int main()
{
    int a=0;
    cin>>a;
    test(VectorCreate(),a);
    return 0;
}

Within the function "test" the second parameter is "transferred" via reference ("int &a") and I would like to transfer the first parameter as a reference, too.
It tried

vector<int>[B]&[/B]VectorCreate();

but it doesn't work.

To pass a vector by reference to a function like your add function you can do this.

//prototype
vector<int> & AddElement(vector<int> & container, int foo);

// definition
vector<int> & AddElement(vector<int> & container, int foo)
{
    container.push_back(foo);
    return container;
}

Edited 5 Years Ago by NathanOliver: n/a

Ok. Thanks for this solution. If I understood it correctly, one could create a vector within a function, but there is no possibility to pass to it with a reference.

But this could be a nice possibility to destroy the vector if there is no use for it any longer.

The only other possibility I know for this is to work with "new" and "delete".
But as I learned, this possibility is not a good style, because there could be made many mistakes.

Edited 5 Years Ago by Sunshine2011: n/a

Ok. Thanks for this solution. If I understood it correctly, one could create a vector within a function, but there is no possibility to pass to it with a reference.

But this could be a nice possibility to destroy the vector if there is no use for it any longer.

The only other possibility I know for this is to work with "new" and "delete".
But as I learned, this possibility is not a good style, because there could be made many mistakes.

Returning a reference to a vector that's created inside the function will not work. When the function ends, your vector gets destroyed just like any other variable. So when you return a reference to it, all you're getting is the invalid point in memory where your vector used to be.

vector<int>& foo(){
  vector<int> myvector;
  return &myvector; //invalid.. the memory address of a vector that's been destroyed is useless
vector<int> foo(){
  vector<int> myvector;
  return myvector;
  //valid, since returning a vector by value causes the vector to be copied into a new vector just before myvector gets destroyed.

Normally you wouldn't use a function to create a vector anyway, since returning it (and thus causing it to be copied) is not efficient. Well maybe if you are using templates. Otherwise, just do

void foo(vector<int>& myvector){
  //modify myvector here--changes will persist in main() since you passed it in by reference.. that is, your function now has the memory address of the vector, and can make permanent changes to it
}

> Normally you wouldn't use a function to create a vector anyway,
> since returning it (and thus causing it to be copied) is not efficient.

Not really.

Dave Abrahams in 'Want Speed? Pass by Value.' - http://cpp-next.com/archive/2009/08/want-speed-pass-by-value explains why:

Be honest: how does the following code make you feel?

std::vector<std::string> get_names();
…
std::vector<std::string> const names = get_names();

Frankly, even though I should know better, it makes me nervous. In principle, when get_names() returns, we have to copy a vector of strings. Then, we need to copy it again when we initialize names, and we need to destroy the first copy. If there are N strings in the vector, each copy could require as many as N+1 memory allocations and a whole slew of cache-unfriendly data accesses as the string contents are copied.

Rather than confront that sort of anxiety, I’ve often fallen back on pass-by-reference to avoid needless copies:

void get_names(std::vector<std::string>& out_param );
…
std::vector<std::string> names;
get_names( names );

Unfortunately, this approach is far from ideal.

  • The code grew by 150%
  • We’ve had to drop const-ness because we’re mutating names.
  • As functional programmers like to remind us, mutation makes code more complex to reason about by undermining referential transparency and equational reasoning.
  • We no longer have strict value semantics for names.

But is it really necessary to mess up our code in this way to gain efficiency? Fortunately, the answer turns out to be no (and especially not if you are using C++0x).
...

(Reading the entire article would be rewarding.)

Edited 5 Years Ago by vijayan121: n/a

> Normally you wouldn't use a function to create a vector anyway,
> since returning it (and thus causing it to be copied) is not efficient.

Not really.

Dave Abrahams in 'Want Speed? Pass by Value.' - http://cpp-next.com/archive/2009/08/want-speed-pass-by-value explains why:

Be honest: how does the following code make you feel?

std::vector<std::string> get_names();
…
std::vector<std::string> const names = get_names();

Frankly, even though I should know better, it makes me nervous. In principle, when get_names() returns, we have to copy a vector of strings. Then, we need to copy it again when we initialize names, and we need to destroy the first copy. If there are N strings in the vector, each copy could require as many as N+1 memory allocations and a whole slew of cache-unfriendly data accesses as the string contents are copied.

Rather than confront that sort of anxiety, I’ve often fallen back on pass-by-reference to avoid needless copies:

void get_names(std::vector<std::string>& out_param );
…
std::vector<std::string> names;
get_names( names );

Unfortunately, this approach is far from ideal.

  • The code grew by 150%
  • We’ve had to drop const-ness because we’re mutating names.
  • As functional programmers like to remind us, mutation makes code more complex to reason about by undermining referential transparency and equational reasoning.
  • We no longer have strict value semantics for names.

But is it really necessary to mess up our code in this way to gain efficiency? Fortunately, the answer turns out to be no (and especially not if you are using C++0x).
...

(Reading the entire article would be rewarding.)

Cool. No one ever told me about this copy elision optimization before. Does this occur with such reliability that I should pass and return any arbitrary object by value?

> Does this occur with such reliability that I should pass and return any arbitrary object by value?

Copy elision is allowed, but not mandated by IS. You can’t write portable code with the assurance that copy elision would be performed.

In practise, mainstream compilers do implement copy elision, at least for RVO and NRVO. However, many opportunities for for copy elision are missed by every compiler.

In general, this is what I follow:
a. Return moveable objects by value. (almost everything in the standard library is moveable.)
b. If the function does not need to modify (a copy of) the object, pass by reference to const.
c. If the function needs to make a mutable copy, pass by value. (If a copy must be made, leaving the details to the compiler would not be less efficient and may result in more optimal code. For example:

std::vector<int> sorted_sequence( std::vector<int> seq )
{
    std::sort( seq.begin(), seq.end() ) ;
    return seq ;
}

Edited 5 Years Ago by vijayan121: n/a

This question has already been answered. Start a new discussion instead.