When you want to return multiple elements you can either use additional output parameters in your functions (passed by reference) or return a tuple. I tend to prefer the later option as it results in more readable code.
Instead of manually managing the memory of your arrays with new
and delete[]
, you can use a std::vector
to achieve an equivalent behavior. Each vector stores its own size so that you don't need to return an additional variable for that.
To summarize, in this case you can just return a tuple of two vectors. In the standard library, two-element tuples are represented with the std::pair
class. Therefore, your function will return a pair of vectors: std::pair<std::vector<int>, std::vector<int> >
. Since that is a lot to type, you better use a typedef
.
This is one possible implementation of your function. Note that you can avoid manually written loops thanks to the standard istream_iterator
class:
typedef std::pair<std::vector<int>, std::vector<int> > Data;
Data read(std::ifstream & ifs)
{
int n;
ifs >> n;
typedef std::istream_iterator<int> in_it;
std::vector<int> a(n);
std::copy(in_it(ifs), in_it(), a.begin());
std::vector<int> b(n);
std::copy(in_it(ifs), in_it(), b.begin());
return Data(a, b);
}
And this is how you would use your function. Notice how you are not returning the size implicitly but you can retrieve it easily through std::vector::size()
.
int main() {
std::ifstream ifs("SOMEFILE.txt");
Data data = read(ifs);
unsigned int n = data.first.size();
std::vector<int> & a = data.first;
std::vector<int> & b = data.second;
return 0;
}
EDIT: Neil's suggestion of using a dedicated struct
scales better and leads to more readable code, so you should certainly consider that as well. In this case your struct would be:
struct Data {
std::vector<int> a, b;
};
And your main
function would be identical except that you have to replace first
and second
with a
and b
.