【问题标题】:Class Function that Inserts values into a sorted array without ruining the order将值插入排序数组而不破坏顺序的类函数
【发布时间】:2020-09-17 04:22:55
【问题描述】:

所以我对这里的逻辑感到非常困惑,我得到了将我的值以 1 比 1 的形式取值并将它们与数组中的元素进行比较的一般想法。如果值较大,则移动到下一个元素,如果值小于或等于该元素,则移动超过 1 个索引的所有元素,并用您的值替换原始索引。我的问题是我不能把最后一部分写成代码,我已经蹲在这里半个小时了。这是我到目前为止所得到的。

void SortedArray::insertVal(int val)
{
    //check for size == capacity
    // if so, use .Expand function to double array capacity, then continue to below.

    //if not continue
    //here is where I am having my issues because I cant get the logic down.
    for (int i = 0; i < capacity; i++)
    {
        if (val > arr[i])
            arr[i] = arr[i + 1];
        else if (val <= arr[i])
        {
            for (int x = 0; x < capacity; x++)
            {
                int temp = arr[i+1];
                arr[i + 1] = arr[i];
                //right about here I realized If I just assign temp to arr[1+2] the value of that index is lost.
            }
        }
    }
}

我只是弯腰,我想在这里检查一下,看看是否有人可以提供帮助,然后我不得不联系我的教授寻求帮助作为最后的手段。 在此先感谢您:)

【问题讨论】:

    标签: c++ function class


    【解决方案1】:

    如果我理解你想要什么,向后读取数组应该可以解决问题。

    for (int i = 0; i < capacity; i++)
    {
       if (val > arr[i])
       {
         for(int x = capacity - 1; x > i; x--)
         {
           arr[x] = arr[x - 1];
         }
         arr[i] = val;
         break;
       }
    }
    

    【讨论】:

    • 这也是我读到的问题。 std::move_backward 看起来在这里可能会有所帮助。
    猜你喜欢
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2012-08-21
    • 2011-09-25
    • 2018-07-24
    • 2021-10-07
    相关资源
    最近更新 更多