如何实现子数组向左移动一个位置

5

如何将数组成员向右移动一个位置?

例如,如果我们有一个大小为n的数组,并且有一个元素,如果我们将成员pos右侧的所有元素向右移动一个位置,我们可以将n-1号成员复制到空元素中,以此类推。

代码:

#include <iostream>

using namespace std;

// we take the position of insertion, then right shift all elements
// then insert the required number

int main() {
    int n = 10;
    int list[n];

    cout << "Enter " << n-1  << " elements:\n";

    for( int i = 0; i < n-1; ++i) {
        cin >> list[i];
    }

    int pos, num;

    cout << "Position ( start: 1 ): ";
    cin >> pos;

    if( pos < n && pos >= 0 ) {
        cout << "No. to be inserted: ";
        cin >> num;

        for( int i = n-2; i >= pos-1; --i) {
            list[i+1] = list[i];
        }
        list[pos-1] = num;

        for( int i = 0; i < n; ++i) {
            cout << list[i] << ' ';
        }

        return 0;
    }
}
  • 我们能不能通过某种方式,一次性将整个子数组向右平移一个位置,将所有元素都右移一位?

  • 另外,我们可以使用向量来实现这个操作吗?向量是更有效或者说更好的方式吗?


9
听起来需要使用 std::rotate - NathanOliver
1
@NathanOliver,那是你吗?Sean Parent? - Borgleader
3
此外,vector::insert会有帮助。 - SCaffrey
如果您需要在中间进行多次插入/删除操作,请使用std::list。请参阅https://dev59.com/TXRB5IYBdhLWcg3w6LV2。 - Support Ukraine
在大多数情况下,即使这与直觉相矛盾,std::vector<> 的性能仍然优于 std::list<>。请参阅 https://www.youtube.com/watch?v=YQs6IC-vgmo。@StillLearning - cdonat
显示剩余5条评论
1个回答

2

首先,C++不支持可变长度数组(VLA)。尽管一些编译器有自己的语言扩展来支持VLA,但最好使用标准C++功能。

因此,不要使用以下方式:

int main() {
    int n = 10;
    int list[n];
    //...

写得好比不写要好。

int main() {
    const int n = 10;
    int list[n];
    //...

通常情况下,如果可能的话,最好使用标准算法而不是循环,因为这可以消除错误。

要在位置pos中插入数组值,您可以使用如下示例程序中所示的方法。对于基本算术类型,您还可以使用标准C函数memmove

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    const size_t N = 10;

    for ( size_t i = 0; i < N; i++ )
    {        
        int a[N] = { 0 };

        auto pos = std::next( std::begin( a ), i );            
        std::copy_backward( pos, std::prev( std::end( a ) ), std::end( a ) );
        *pos = i + 1;

        for ( int x : a ) std::cout << x << ' ';
        std::cout << std::endl;
    }

    return 0;
}

它的输出结果为

1 0 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 0 3 0 0 0 0 0 0 0 
0 0 0 4 0 0 0 0 0 0 
0 0 0 0 5 0 0 0 0 0 
0 0 0 0 0 6 0 0 0 0 
0 0 0 0 0 0 7 0 0 0 
0 0 0 0 0 0 0 8 0 0 
0 0 0 0 0 0 0 0 9 0 
0 0 0 0 0 0 0 0 0 10 

关于标准容器std::vector,它有方法允许插入新元素。但与数组相比,这些方法会扩大向量。
以下是std::vector的一些方法,可用于插入一个元素。
iterator insert(const_iterator position, const T& x);
iterator insert(const_iterator position, T&& x);

在技术层面上,向量与数组的工作方式相同,但是向量可以动态地扩大所使用的内存。


谢谢!实际上这是一项学校作业,我们必须使用循环。在这种情况下,向量方法是否更好? - Max Payne
1
@Tim 如果数组不是很大且需要固定数量的元素,则最好使用数组。否则,请使用std::vector。请注意,使用容器std::array比普通数组更好。 - Vlad from Moscow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接