数组C ++的PushFront方法 [英] PushFront method for an array C++

查看:326
本文介绍了数组C ++的PushFront方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我会发布一些我的家庭作业。我失去了它。我只需要真正高效。不使用任何stls,boosts等。通过这篇文章,我希望有人可以帮助我计算出来。

I thought i'd post a little of my homework assignment. Im so lost in it. I just have to be really efficient. Without using any stls, boosts and the like. By this post, I was hoping that someone could help me figure it out.

bool stack::pushFront(const int nPushFront)
{     
     if ( count == maxSize ) // indicates a full array
     {
        return false;
     }
     else if ( count <= 0 )
     {
	     count++;
	     items[top+1].n = nPushFront;
	     return true;
     }
     ++count;
     for ( int i = 0; i < count - 1; i++ )
     {
	     intBackPtr = intFrontPtr;
	     intBackPtr++;
	    *intBackPtr = *intFrontPtr;
     }
     items[top+1].n = nPushFront;
     return true;    
}

我不知道我的生活是否正确!我希望这样做正确,有指针和所有

I just cannot figure out for the life of me to do this correctly! I hope im doing this right, what with the pointers and all

int *intFrontPtr = &items[0].n;
int *intBackPtr  = &items[capacity-1].n;

我试图想到这个pushFront方法像一个数组向右移n单位。 ..我只能似乎在一个数组是满的。

Im trying to think of this pushFront method like shifting an array to the right by 'n' units...I can only seem to do that in an array that is full. Can someone out their please help me?

推荐答案

你不需要任何指针来移动数组。只需使用simple for语句:

You don't need any pointers to shift an array. Just use simple for statement:

int *a; // Your array
int count; // Elements count in array
int length; // Length of array (maxSize)

bool pushFront(const int nPushFront)
{
    if (count == length) return false;
    for (int i = count - 1; i >= 0; --i)
        Swap(a[i], a[i + 1]);
    a[0] = nPushFront; ++count;
    return true;
}

这篇关于数组C ++的PushFront方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆