c++ - 在 C++ 中,如何在列表中每次运行连续零时删除除 x 之外的所有零?

标签 c++ algorithm list c++11 erase-remove-idiom

每次运行 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 的原因很简单,int0 之间没有隐式转换> 和一个 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/

相关文章:

java - 反转二叉树的交替级别

python - 是否可以在不迭代的情况下将列表类型转换为生成器?

html - 正确 float 不同高度的div

c++ - AutoCAD C++ AcDbEntity 何时需要打开读取?

c++ - 一种无需最大化内存即可实时缓冲高清视频的有效方法

c++ - 在 gdb 中找不到 GLIBCXX

java - 是否有任何用于折线简化的开源 Java 库?

c++ - 当具有 std::map<int,std::ofstream> 成员时,类不从 dll 导出

php - 如何仅提取数组键(字符串)的一部分并更改其大小写

list - 在 Spring MVC 中动态生成可用语言列表