【问题标题】:Left/right shift for inserting into an ordered vector用于插入有序向量的左移/右移
【发布时间】:2014-12-01 03:30:25
【问题描述】:

对于编程任务,我们被要求创建一个有序向量类。我的问题是关于我的“leftShift”功能。

我的第一个代码编译良好,但在使用测试文件运行时会因索引越界异常而崩溃。

**private E LeftShift(int index){
        E Temp = arrayFirst[index];
        for (int x = index ; x<= size -1 ; x++){
            arrayFirst[x] = arrayFirst[x+1];
        } 
        return Temp;**

这让我很头疼,但经过反复试验后,我只是删除了一个 = 以使其正常运行。

**private E leftShift(int index){
        E Temp = arrayFirst[index];
        for (int x = index ; x < size -1 ; x++){
            arrayFirst[x] = arrayFirst[x+1];
        }
        return Temp;**

虽然它确实有效,但我希望更好地了解为什么我的第一个代码会崩溃,以及是什么让第二个代码可以正常工作。任何解释都非常感谢!

【问题讨论】:

  • leftShift被调用后,向量的最后两个元素相同是不是期望的结果?

标签: java vector data-structures ordereddictionary


【解决方案1】:

在第一个代码块中,x 将迭代直到x &lt;= size - 1 为假(直到x &gt; size - 1)。

因此在最后一次迭代x = size - 1。在循环中,在最后一次迭代中,您访问arrayFirst[x+1],即arrayFirst[(size - 1) + 1] = arrayFirst[size]

这超出了范围。第二个代码块中不会出现这个错误,因为你在x == size - 1时停止了,所以这个错误的迭代不会发生。

【讨论】:

    猜你喜欢
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2011-06-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    相关资源
    最近更新 更多