How to implement one-position sub-matrix offset

How can we shift the elements of an array by one position?

For example, if we have an array n with one element empty , and we shift all elements to the right of the pos element at the same position, we can copy the n-1st member to an empty element, etc.

code:

#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;
    }
}
  • But can we, in some way, s move the entire submatrix in one go, sliding all the members to the right by one?

  • Can we also implement this with vectors ? And will vectors be more efficient or better to achieve this?

+4
1

, ++ Variable Length Arrays (VLAs). , VLA, ++.

,

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);

, , , .

+2

Source: https://habr.com/ru/post/1623753/


All Articles