【发布时间】:2021-08-12 10:18:30
【问题描述】:
所以这是一个练习,我必须将std::vector<int> 格式化为std::string。该练习要求我们仅使用 stl 算法,并且不允许使用 for 循环。 std::for_each 是允许的,因为它也是算法的一部分,但他们也不想让我们使用它。
输入总是排序的,并且不包含任何重复。
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]" |
我已经在研究 std::search 和 std::adjacent_find 是否可以使用它们,但我认为它们不会满足我的需求。
这是我尝试过的。我也不认为这是解决这个问题的正确方法,因为完整的练习是关于标准算法的,我在这里没有使用任何。任何关于什么 stl 算法在这种情况下可以派上用场的建议,将不胜感激。
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();
}
【问题讨论】:
-
“练习要求我们只使用 stl 算法”哇,还有希望:)。请展示你的尝试。我们不会为您写作业,但如果您给我们一些工作,我们可以提供帮助。 meta.stackoverflow.com/questions/334822/…
-
这篇文章能回答你的问题吗? stackoverflow.com/questions/8581832/…
-
@Attis 不,这个问题的重点是将连续范围“压缩”成与非连续部分不同的格式。
-
一旦连续范围被“压缩”,使用
std::copy()和输出流迭代器可以很容易地处理输出。需要进行一些调整,因为在输出int(例如从向量)之后,以下字符在某些情况下需要是',',而在某些特定情况下需要是其他字符。 -
如果你已经有一个普通的
for循环,那么尝试将循环体转换为一个只接受一个参数(当前值)的函数。一旦你有了它,你可以用std::for_each调用替换循环。
标签: c++