Bo Persson said:
Could be, but perhaps we should save that until we see that there is
a performance problem? Michael didn't say how many millions of
doubles the vector is expected to contain.
Until we know that, returning a vector is perfectly good, especially
if it makes the code easier to read and understand.
I don't like premature optimization, but let's not prematurely pessimize
our program either. Because this particular issue requires an interface
change, it bears more scrutiny up front.
Mirek's suggestion not only is likely to perform better, it is also not
likely to perform any worse, and it is more idomatic, if a little C like.
Some other possible solutions:
const vector<double>& myfunction( /*params*/ ) {
static vector<double> result;
result.clear();
// fill result
return result;
}
The above has the benefit of being pratically a drop-in replacement for
the OPs function signature, but has the drawback of keeping a possible
extra copy of the result indefinitely.
Another solution which fits better with the rest of the library would be:
template < typename OutIt >
void myfunction( OutIt begin, /*params*/ );
This solution allows the caller to choose the container that best suits
his needs rather than having to use vector.
Another:
struct MyGenerator {
MyGenerator( /*params*/ );
double operator()(); // returns the next double in the list
};
The above can be used with either the generate or generate_n functions,
but would require the caller to know how many elements should exist.
Lastly, we can make an iterator:
class MySequence: public std::iterator< std::forward_iterator_tag,
double >
{
public:
MySequence(); // sentinel
explicit MySequence(/*params*/); // start the sequence
double operator*(); // return the current value in the sequence
MySequence& operator++(); // go to the next value in the sequence
MySequence operator++(int);
friend bool operator==(const MySequence& lhs, const MySequence& rhs);
// return true if the both objects point to the same element
// in the sequence.
};
bool operator!=(const primes& lhs, const primes& rhs) {
return !(lhs == rhs);
}
This can be used directly in other algorithms without having to ever
create a container holding all the elements. (I have, for example,
something like the above for generating primes and fibonacci numbers.)
But it may be too heavy weight for the OPs situation.