从c ++中的排序整数向量获得连续范围

时间:2012-07-26 04:31:11

标签: c++

从整数向量中提取连续范围

我已经对矢量(非重复值)进行了排序,如[1,2,3,6,7,8,12,15]

我需要从像1-3,6-8,12-15这样的向量中提取每个范围到类似的字符串:

“0-3,6-8,12,15”

1 个答案:

答案 0 :(得分:0)

我最近熟了这个代码。它从文件中读取,而不是字符串,它输出到文件。我相信你可以根据自己的需要进行修改。

#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;
}