#include "pch.h" #include <iostream> #include <Windows.h> using namespace std; void sdvig(int * m, int size, int sdv) { int max = *m; bool s = false; for(int i = 1; i < size; i++) { if (m[i] > max) max = m[i]; } for (int * p = m; *p <= size; p++) { *p = (p - m) + (sdv + 1); } int num = 0; while (!s) { for (int i = 0; i < size; i++) { if (m[i] <= max) num++; else s = 1; } } for (int * p = m + num; *p <= size; p++) { *p = (p - (m + num)) - 5; } for (int j = 0; j < size; j++) cout << m[j] << endl; cout << " " << num << endl; } int main(int argc, const char * argv[]) { int m[5] = { 1, 2, 3, 4, 5 }; sdvig(m, 5, 2); cin.get(); return 0; } 

I have such a problem: I need to move all the elements of the array to the left by 2. That is, if the initial array is {1, 2, 3, 4, 5}, then it should turn out {3, 4, 5, 1, 2}. What's my mistake? Correct, if not hard.

  • What is the purpose of the search for the maximum element of an array in the task of cyclic shift ??? - AnT
  • I had such an algorithm: 1) Find the max element of the initial array. 2) Find how many elements are up to the max element of the inclusive initial array. (num) 3) Move all elements of the initial array by 2, thereby obtaining the second array. 4) Replace all items after num with the initial ones. - Vyacheslav Zakharchenko

2 answers 2

To do without any temporary arrays, the easiest way to deploy an array is first the whole and then two parts:

 void reverse(int * a, int begin, int end) { for(int i = begin, j = end; i < j; ++i, --j) { int t = a[i]; a[i] = a[j]; a[j] = t; } } void rotate(int * a, int size, int count) { reverse(a,0,size-1); reverse(a,0,count-1); reverse(a,count,size-1); } 

This, of course, if religion (or teacher) categorically prohibits the use of the standard function rotate() ...

    To shift the array is better to use memcpy and memmove .

     #include <cstring> #include <iostream> void shift_left(int *arr, int size, int offset) { // массив для хранения элементов, которые перенесутся в конец int *tmp = new int[offset]; // копируем во временный массив элементы, которые перенесутся в конец std::memcpy(tmp, arr, offset * sizeof(int)); // сдвигаем элементы, начиная с arr[offset], на offset влево std::memmove(arr, &arr[offset], (size - offset) * sizeof(int)); // копируем элементы из временного массива в конец исходного std::memcpy(&arr[size - offset], tmp, offset * sizeof(int)); delete[] tmp; } int main(int argc, char *argv[]) { int m[5] = {1, 2, 3, 4, 5}; shift_left(m, 5, 2); for (int i = 0; i < 5; ++i) { std::cout << m[i] << ' '; } std::cout << std::endl; }