So this is an exercise where I have to format a std::vector<int>
into a std::string
. The exercise requires us to only use stl algorithms, and we're not allowed to use for loops. std::for_each
is allowed since it's part of algorithm too, but they rather not have us use it either.
The inputs are always sorted, and don't contain any duplicates.
Input std::vector<int> |
Output std::string |
---|---|
{ 4, 8, 12} |
"4, 8, 12" |
{ -20, -19, .., .., 10, 11} |
"[-20, 11]" |
{ -5, 8, 9, 10, 11, 12, 21} |
"-5, [8, 12], 21" |
{ -2, 5, 6, 7, 10, 11, 12 } |
"-2, [5, 7], [10, 12]" |
I was already looking into std::search
and std::adjacent_find
if I could use those, but I don't think they'll do what I need.
This is what I've tried. I also don't think this is a proper approach to solve this, since the complete exercise is meant to be about std algorithms, and I'm not using any here. Any suggestions to what stl algorithm could be handy in this case, would be greatly appreciated.
std::string FormatLine(int lineNumber)
{
std::vector<int> input = { -2, 5, 6, 7, 9, 11, 12, 13 };
std::stringstream output{};
int startNumber { input[0] };
bool isRange{ false };
for (int i{ 1 }; i < input.size(); ++i)
{
const int lastNumber = input[i - 1];
// continue if its a incrementing sequence
if (input[i] - 1 == lastNumber)
{
// if no range has been started yet, start one
if (!isRange)
{
output << "[" << startNumber << ", ";
isRange = true;
}
continue;
}
output << lastNumber;
// if a range was started, close it with the last element of the range
if (isRange)
{
output << "],";
isRange = false;
}
// just a number so add a comment
else
output << ", ";
startNumber = input[i];
}
// dont forget to add the last element
output << input.back();
// if it was still in a range, add closing bracket
if (isRange)
output << ']';
return output.str();
}