每次运行 x
或 C++ 列表中的多个连续零,我想删除运行中的所有零,x
除外他们中的。如果x = 0
,然后删除所有零。
我在想一个接受列表的 C++ 函数,list<int> L
, 和一个数字 int x
, 作为输入。
例如,设L = {7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8}
.
- 如果
x = 0
, 然后返回L = {7, 12, 2, 27, 10, 8}
- 如果
x = 1
, 然后返回L = {7, 0, 12, 0, 2, 0, 27, 10, 0, 8}
- 如果
x = 2
, 然后返回L = {7, 0, 12, 0, 0, 2, 0, 0, 27, 10, 0, 0, 8}
- 如果
x = 3
, 然后返回L = {7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 8}
- 如果
x = 4
, 然后返回L = {7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8}
(与原版相同L
) - 如果
x >= 5
, 然后返回原始L
因为没有 5 个或更多个连续零的运行。
几个月前,我使用 Python ( stackoverflow.com/questions/11732554/... ) 问了上面同样的问题,并得到了很好的答案。现在我想用 C++ 完成这个任务。
我们将不胜感激任何帮助。
最佳答案
这里有一些代码可以完成这项工作:
void DeleteAllZerosInARow(std::list<int>& theList, int x)
{
if(x == 0)
{
theList.remove(0);
return;
}
int streak = 0;
std::list<int>::iterator itor = theList.begin();
while(itor != theList.end())
{
if(*itor == 0)
++streak;
else
streak = 0;
if(streak > x)
itor = theList.erase(itor);
else
++itor;
}
}
基本上,您计算一行中有多少个零,如果您是 > x
,则删除它们,否则继续迭代列表。
给出以下输出:
- 0 :
7,12,2,27,10,8
- 1 :
7,0,12,0,2,0,27,10,0,8
- 2 :
7,0,12,0,0,2,0,0,27,10,0,0,8
- 3 :
7,0,12,0,0,2,0,0,0,27,10,0,0,0,8
- 4 :
7,0,12,0,0,2,0,0,0,27,10,0,0,0,0,8
- 5 :
7,0,12,0,0,2,0,0,0,27,10,0,0,0,0,8
这取决于你的风格,remove_if
可能是更 C++
的方式,但我发现直接操作值更清晰,但它不会涉及一个新的数据类型(一个struct
来跟踪你遇到的0
的数量)。
代码无法使用 NTL::ZZ
的原因很简单,int
、0
之间没有隐式转换> 和一个 NTL::ZZ
大数字,因此它不能 remove(0)
。你可以做的可能是:
if(x == 0)
{
static ZZ zero; // default value is 0, static so that it is only constructed once
theList.remove(zero); // remove all items who are equal to "zero"
return;
}
关于c++ - 在 C++ 中,如何在列表中每次运行连续零时删除除 x 之外的所有零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14344831/