extracting continuous ranges from a integer vector
I have sorted vector(with non-repeated values) like this [1,2,3,6,7,8,12,15]
I need to extract every range from such vector like 1-3,6-8,12-15 in to a string like:
"0-3,6-8,12,15"
extracting continuous ranges from a integer vector
I have sorted vector(with non-repeated values) like this [1,2,3,6,7,8,12,15]
I need to extract every range from such vector like 1-3,6-8,12-15 in to a string like:
"0-3,6-8,12,15"
I recently cooked this code. It reads from a file, and instead of string it outputs to a file. I am sure you can modify it to suit your needs.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
template <typename T>
inline T convert(string &s)
{
T out;
istringstream ss(s);
ss >> out;
return out;
}
int main()
{
ifstream infile("input.txt");
ofstream outfile("output.txt");
string cur_line, last_line;
int cur, last;
if (infile.good()) {
getline(infile, cur_line);
cur = convert<int>(cur_line);
outfile << cur_line << ',';
last = cur;
}
while(getline(infile, cur_line))
{
cur = convert<int>(cur_line);
if (cur != last + 1) {
outfile << last_line << '\n';
outfile << cur_line << ',';
}
last = cur;
last_line = cur_line;
}
outfile << last_line;
infile.close();
outfile.close();
return 0;
}