Sending a vector from a function

How to translate the following Java code in C ++?

Vector v;
v = getLargeVector();
...
Vector getLargeVector() {
    Vector v2 = new Vector();
    // fill v2
    return v2;
}

So here vis a link. The function creates a new Vector object and returns a link to it. Nice and clean.

However, consider the following C ++ mirror-translation:

vector<int> v;
v = getLargeVector();
...
vector<int> getLargeVector() {
    vector<int> v2;
    // fill v2
    return v2;
}

Now it vis a vector object, and if I understand correctly, it v = getLargeVector()will copy all the elements from the vector returned by the function to v, which can be expensive. In addition, the stack is created v2, and its return will lead to another copy (but, as I know, modern compilers can optimize it).

This is currently what I am doing:

vector<int> v;
getLargeVector(v);
...
void getLargeVector(vector<int>& vec) {
    // fill vec
}

But I do not consider this an elegant solution.

, : ( )? , . , , .

+3
6

++ , , .

:

vector<int> v(getLargeVector());

, , .

+6
void getLargeVector(vector<int>& vec) { 
    // fill the vector
} 

. ++ 0x , .

+3

RVO , , RVO . RVO - , , , , RVO- RVO . , :

MyBigObject Gimme(bool condition)
{
  if( condition )
    return MyBigObject( oneSetOfValues );
  else
    return MyBigObject( anotherSetOfValues );
}

... RVO- . , , , , RVO , .

, ( ), , , , , , : , . , , , RVO. , . :

#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

template<typename Iter> Iter PopulateVector(Iter it, size_t howMany)
{
    for( size_t n = 0; n < howMany; ++n )
    {
        *(it++) = n;
    }

    return it;
}

int main()
{
    vector<int> ints;
    PopulateVector(back_inserter(ints), 42);
    cout << "The vector has " << ints.size() << " elements" << endl << "and they are..." << endl;
    copy(ints.begin(), ints.end(), ostream_iterator<int>(cout, " "));
    cout << endl << endl;

    static const size_t numOtherInts = 42;
    int otherInts[numOtherInts] = {0};
    PopulateVector(&otherInts[0], numOtherInts);
    cout << "The other vector has " << numOtherInts  << " elements" << endl << "and they are..." << endl;
    copy(&otherInts[0], &otherInts[numOtherInts], ostream_iterator<int>(cout, " "));

    return 0;
}
+2

? , , , ?

If you don't want to worry about memory management, then a smart pointer is the best way. If you are not comfortable with pointer syntax, use links.

+1
source

You have a better solution. Passing by reference is a way to deal with this situation.

+1
source

It looks like you can do it with a class ... but it might be unnecessary.

#include <vector>
using std::vector;

class MySpecialArray
{
    vector<int> v;
public:
    MySpecialArray()
    {
        //fill v
    }
    vector<int> const * getLargeVector()
    {
        return &v;
    }
};
0
source

Source: https://habr.com/ru/post/1727723/


All Articles