在C中,如何在列表中的每个连续零运行中删除除x之外的所有零?
对于C中列表中x或更多连续零的每次运行,我想删除运行中除了x之外的所有零.如果x = 0,则删除全零.
我在想一个带有列表的C函数,列表< int> L和数字int x作为输入. 例如,令L = {7,12,2,27,10,0}. >如果x = 0,则返回L = {7,8} 几个月前,我用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,8 这取决于你的风格,remove_if可能是更多的C方式,但我发现直接操作值更清楚,它不涉及一个新的数据类型(一个结构来跟踪你的数量0)遇到). 使用NTL :: ZZ代码不起作用的原因很简单,在int,0和NTL :: ZZ大数字之间没有隐式转换,因此它不能删除(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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |