There is an array:

18.666667 -9216.000000 -4480.000000 -2389.333333 -2016.000000 448.000000 

How to rearrange 18.6 to a place between -2016 and 448 (to the penultimate position)?

Closed due to the fact that the essence of the issue is not clear to the participants Denis Bubnov , Pavel Mayorov , user194374, Kromster , Alexey Shimansky 22 Dec '16 at 14:02 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

    5 answers 5

    Save 18.6 in the time variable, shift everything in the array from -9216 ... to -2016 ... inclusive by one element, and put the stored value in the right place ...

    • Perhaps this is an XY problem, and in fact the author simply needs to sort the array? - Yaant
    • @Yaant possible. But I am not Nostradamus. Sort and move items are completely different tasks. If there is no clear TZ - the result is HZ :) And what if the author needs a cyclical shift? :) - Harry
    • No, it works. I thought they would write a code according to which I would understand, but that was enough. I sketched myself and it seems to work. Thank. - Andrey
    • double tmp = a[0]; for(int i = 1; i <= 4; ++i) a[i-1]=a[i]; a[4] = tmp; Theoretically, you can use memmove . - Harry

    You need to create a new variable in which to save the penultimate element (otherwise it will disappear). Next, set the last item instead of the last one. And the last element is equal to that new variable.

      You can try to shift the array element to k positions using the method std::rotate: more detail here

        For arithmetic types, it is easiest and more efficient to use the standard function std::memmove , declared in the header file <cstring> .

        For example,

         #include <iostream> #include <cstring> int main() { double a[] = { 18.666667, -9216.000000, -4480.000000, -2389.333333, -2016.000000, 448.000000 }; for (double x : a) std::cout << x << ' '; std::cout << std::endl; size_t src = 0, dsn = 4; double tmp = a[src]; std::memmove(a + src, a + src + 1, ( dsn - src) * sizeof( double )); a[dsn] = tmp; for (double x : a) std::cout << x << ' '; std::cout << std::endl; } 

        Output of the program to the console

         18.6667 -9216 -4480 -2389.33 -2016 448 -9216 -4480 -2389.33 -2016 18.6667 448 
           std::sort(std::begin(arr), std::end(arr)); std::sort(arr.begin() arr.end()); std::sort(pointer, pointer + arrsize); 

          Depending on the type of array used and the version of the standard.