Code:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
#include <string>
#include <sstream>
#include <map>
using namespace std;
void MakeOutput(string fileName, const map<int, string>& mapf1, ostream& out)
{
ifstream file(fileName);
if (file.is_open())
{
map<int, string>::const_iterator it = mapf1.begin();
map<int, string>::const_iterator End = mapf1.end();
int lo = max(0, it->first - 6);
int hi = 6 + it->first;
int number;
double value;
ostringstream collector;
while (file >> number >> value)
{
if (number < lo)
{
//Display numbers below our range
out << number << "," << value << endl;
}
else if (lo <= number && number <= hi)
{
if (number == it->first)
{
//Display linked value
out << number << "," << it->second << "," << value << endl;
}
//Collect values in our range
collector << number << "," << value << ",";
}
else
{
// Display collected values.
string coll = collector.str();
if (!coll.empty())
{
coll.pop_back(); // Remove the extra comma
out << coll << endl;
collector.str("");
}
// Advance the map
if (it != End && ++it != End)
{
lo = max(0, it->first - 6);
hi = 6 + it->first;
}
else
{
//lo needs to be high to capture any leftovers in file2.
lo = numeric_limits<int>::max();
}
// Handle the current number with the new range.
if (lo <= number && number <= hi)
{
collector << number << "," << value << ",";
}
else
{
out << number << "," << value << endl;
}
}
}
}
else
{
cout << "Couldn\'t open file 2: " << fileName << endl;
}
}
371,0.4
378,close,0.691
372,0.123,373,0.239,374,0.759,375,0.774,376,0.748,377,0.675,378,0.691,379,0.272,380,0.502,381,0.969,382,0.921,383,0.173,384,0.679
385,0.601
386,0.578
387,0.476
388,0.998
389,0.777
390,0.952
391,0.554
392,0.998
393,0.972
394,0.053
395,0.294
396,0.742
397,0.179
398,0.689
399,0.885
400,0.026
401,0.644
408,close,0.41
402,0.13,403,0.131,404,0.429,405,0.86,406,0.702,407,0.309,408,0.41,409,0.674,410,0.957,411,0.886,412,0.664,413,0.604,414,0.867
415,0.294
416,0.647
417,0.386
418,0.463
419,0.667
420,0.461
:
:
Pretty clean solution I think, as long as it's correct.