In C++, whenever a function creates many (hundreds or thousands of) values, I used to have the caller pass an array that my function then fills with the output values:
void computeValues(int input, std::vector<int>& output);
So, the function will fill the vector output
with the values it computes. But this is not really good C++ style, as I'm realizing now.
The following function signature is better because it doesn't commit to using a std::vector
, but could use any container:
void computeValues(int input, std::insert_iterator<int> outputInserter);
Now, the caller can call with some inserter
:
std::vector<int> values; // or could use deque, list, map, ...
computeValues(input, std::back_inserter(values));
Again, we don't commit to using std::vector
specifically, which is nice, because the user might just need the values in a std::set
etc. (Should I pass the iterator
by value or by reference?)
My question is: Is the insert_iterator
the right or standard way to do it? Or is there something even better?
EDIT: I edited the question to make it clear that I'm not talking about returning two or three values, but rather hundreds or thousands. (Imagine you have return all the files you find in a certain directory, or all the edges in a graph etc.)