c++ - 移动数组中的元素 C++

标签 c++ algorithm

我为我的堆栈对象类开发了一种称为“旋转”的方法。我所做的是,如果堆栈包含元素:{0,2,3,4,5,6,7},我需要向前和向后旋转元素。

如果我需要向前旋转 2 个元素,那么数组中会有 {3,4,5,6,7,0,2}。如果我需要向后旋转,或 -3 个元素,那么,查看原始数组,它会是 {5,6,7,0,2,3,4}

所以我开发的方法工作正常。 IMO 的效率非常低下。我想知道是否可以使用 mod 运算符环绕数组?或者如果他们是我还没有意识到的无用代码,等等。

我想我的问题是,如何简化此方法?例如使用更少的代码。 :-)

void stack::rotate(int r)
{
    int i = 0;
    while ( r > 0 ) // rotate postively.
    {
        front.n = items[top+1].n;
        for ( int j = 0; j < bottom; j++ )
        {
            items[j] = items[j+1];                                  
        }
        items[count-1].n = front.n;
        r--;
    }

    while ( r < 0 )  // rotate negatively.
    {
        if ( i == top+1 )
        {
            front.n = items[top+1].n;  
            items[top+1].n = items[count-1].n; // switch last with first
        }

        back.n = items[++i].n; // second element is the new back
        items[i].n = front.n; 
        if ( i == bottom )
        {
            items[count-1].n = front.n; // last is first
            i = 0;  
            r++;   
            continue;
        }
        else
        {
            front.n = items[++i].n;
            items[i].n  = back.n;
            if ( i == bottom )
            {
                i = 0;
                r++; 
                continue;
            }
        }
    }
}

最佳答案

您可以更改“开始”的定义,而不是移动堆栈中的所有项目。有一个代表堆栈中第一项的索引,开始时为 0,只要您想旋转堆栈,就可以使用模块化算法对其进行添加和减去。

请注意,如果您采用这种方法,您不应该让您的类的用户访问底层数组(无论如何您真的应该......)。

关于c++ - 移动数组中的元素 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1616086/

相关文章:

c++ - 增强程序 - 完全失败

c++ - 查明 IP 地址是否可达的最佳和快速方法

algorithm - 检测来自 YouTube 的重复视频

python - 将数组拆分为子数组 5 次,同时在所有子数组中保留唯一的对

c++ - 你如何在 C++ 中实现阶乘函数?

c++ - 不使用 boost 绑定(bind)

c++ - 比 map<string, map<string, vector> 更好的东西

php - 在倒排索引算法中避免竞争条件的技术

algorithm - 如果 f(n) 是 Θ(h(n)) 并且 g(n) = O(h(n)) 那么 f(n) + g(n) 就是 Θ(h(n))。对或错

c++ - 在函数类中使用 push_back 更新指针 vector 的大小