0
我需要編寫一個程序來打印文件中特定單詞的行號(升序)。該方案的實施例輸出將是:更有效的方法來查找矢量中的連續數字?
Hello 1, 3, 5-6, 8, 10-15.
// 5-6 represents 5, 6 (consecutive numbers)
的行號存儲在排序vector<int>
,沒有重複。我創造了一個解決方案,但我的直覺告訴我我可以做得更好。我希望得到一些反饋。此外,以下代碼僅處理行號。這個詞在另一種方法中找到。
void IndexPager::createLines(vector<int>& vec, string& line)
{
int start = *vec.begin(), end = -1, offset = 0; // initial offset to start
for (vector<int>::const_iterator itr = vec.begin();
itr != vec.end() + 1; itr++)
{
if (*itr == start + offset && itr != vec.end())
{
end = *itr;
++offset;
} // check if line numbers are consecutive and not reading at end of vector
else // not consecutive
{
if ((end != -1) && (end != start))
{
line.append(intToString(start) + "-");
line.append(intToString(end));
} // if there existed consecutive numbers, display with dash
// must be difference of at least 1
else // else, there were no consecutive numbers
line.append(intToString(start));
if (itr != vec.end()) // check if not at end of vector
line.append(", ");
else // reached end of vector
line.append(".");
start = *itr; // set start to next line number. Soft reset.
offset = 1; // change default offset to 1. 0 for first case.
end = -1;
} // not consecutive
} // Get all line numbers and format for proper output
} // createLines()
如果你想對工作代碼提供一些反饋,可以考慮將它發佈在https://codereview.stackexchange.com/。但是,您將不得不包含完全可編譯的解決方案;閱讀幫助中心:https://codereview.stackexchange.com/help – user2296177