I find myself frequently doing something like this to concatenate several vectors that are returned from functions (possibly class functions):
#include <vector>
#include <iostream>
using namespace std;
vector<int> v1;
const vector<int>& F1() {
cout << "F1 was called" << endl;
/*Populate v1, which may be an expensive operation*/
return v1;
}
int main() {
vector<int> Concat;
Concat.insert(Concat.end(), F1().begin(), F1().end());
/*Do something with Concat*/
return 0;
}
As I expected, F1()
is called twice, which may be undesirable if it is an expensive function call. An alternative is to copy the return value of F1()
into a temporary vector which would only require one function call, but would incur a copy operation which might be undesirable if the vector is large. The only other alternative I can think of is to create a pointer to a temporary vector and assign the return value of F1()
to it like this:
int main() {
vector<int> Concat;
const vector<int>* temp = &F1();
Concat.insert(Concat.end(), temp->begin(), temp->end());
/*Do something with Concat*/
return 0;
}
Is this really the best solution? The use of a temporary variable seems cumbersome, especially if I need to concatenate several vectors. I also feel like there should be a way to do this using references instead of pointers. Any suggestions?