Reading From Files

!!!!
Last edited on
11111
Last edited on
If you have two sorted sequences it is job for merge: https://en.wikipedia.org/wiki/Merge_algorithm
The general merge algorithm has a set of pointers p0..n that point to positions in a set of lists L0..n. Initially they point to the first item in each list. The algorithm is as follows:

While any of p0..n still point to data inside of L0..n instead of past the end:

1) do something with the data items p0..n point to in their respective lists
2) find out which of those pointers points to the item with the lowest key; advance one of those pointers to the next item in its list


Also look at this: http://en.cppreference.com/w/cpp/algorithm/merge
It comes with reference imlementations you can stydy and try to understand.

An example of merging two input streams in one output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>

int main()
{
    std::istringstream f1 {"1 4 5 18"};
    std::istringstream f2 {"2 3 15 16"};
    std::ostringstream out;
    std::merge(std::istream_iterator<int>(f1), std::istream_iterator<int>(),
               std::istream_iterator<int>(f2), std::istream_iterator<int>(),
               std::ostream_iterator<int>(out, ", "));
    std::cout << out.str();
}
http://coliru.stacked-crooked.com/a/fd71f0d173ccf36a

I cheated a little and made input values to be separated by space, but it is not that hard to make stream to threat comma as space too.
Topic archived. No new replies allowed.