1. ## merging n vectors

I have n sorted streams. I was wondering if there was a general way to merge them without the code growing. Here is what I have for 2 streams
Code:
```int merge_and_print(saga::job::istream out, saga::job::istream out2){
int temp=-1, temp2=-1;
if(!out.eof() && !out.fail()){
out >> temp;
}
if(!out2.eof() && !out2.fail()){
out2 >> temp2;
}
while(1){
if(temp == -1 && temp2 == -1){ std::cout << std::endl << "Done reading output" << std::endl; return 1;}
if(temp == -1){
std::cout << temp2 << " ";
while(!out2.eof() && !out2.fail()){
out2 >> temp2;
std::cout << temp2 << " ";
}
std::cout << std::endl << "Done reading output" << std::endl; return 1;
}
else if(temp2==-1){
std::cout << temp << " ";
temp = -1;
while(!out.eof() && !out.fail()){
out >> temp;
std::cout << temp << " ";
}
std::cout << std::endl << "Done Reading output" << std::endl; return 1;
}
else if(temp <= temp2){
std::cout << temp << " ";
if(!out.eof() && !out.fail()){
out >> temp;
}
else temp = -1;
}
else if(temp2 < temp){
std::cout << temp2 << " ";
if(!out2.eof() && !out2.fail()){
out2 >> temp2;
}
else temp2=-1;
}
}
return 0;```

2. Why not load the data into actual vectors and merge the data in the vectors with an algorithm from <algorithm>?

BTW, does your current code repeat the last value of the streams an extra time?

3. Calling two input streams 'out' and 'out2' is just too weird.

A vector of N stream references perhaps?

4. I can't load the values from the stream into a vector and then merge because the streams are from jobs that are running in parallel. So I don't think I can do that, but I'm not sure. I think the best way would be a vector of n streams. Thanks. I'll try that.

5. You can do it with some thread security if you want. But they're generally expensive and you have to ask yourself if it's worth it.

6. Originally Posted by linuxdude
I can't load the values from the stream into a vector and then merge because the streams are from jobs that are running in parallel. So I don't think I can do that, but I'm not sure. I think the best way would be a vector of n streams. Thanks. I'll try that.
For better performance when merging from many streams, store pointers to the streams in heap order inside the vector.