c++11 - C++ Reverse a smaller range in a vector -


what best way following?

i reverse smaller range in vector , haven't found better solution this: extract smaller range newly created vector, reverse , add newly created vector @ former position in original vector.

another way explain want this:

original vector: 1 2 3 4 5 6 7 8 9 10 11.

wanted result:   1 2 3 4 5 6 7 10 9 8 11.

  1. copy 10, 9, 8 in order new vector 3 element or copy element 8, 9, 10 new vector reverse it. original vector consists of 9 elements because elements 8, 9, 10 erased in procedure.

2.the new vector 3 elements 10, 9, 8 copied/appended original vector @ position 8 vector or element element @ position 8, 9, 10 respectively.

i sure there better solutions method mentioned above.

you in fact write in-place swap,

  • that gets last , first index swap,
  • swap these,
  • decreases last index , increases first index,
  • and repeats until last_index - 1 <= first_index.

now, sounds less copying me, stroustrup himself once said:

i don't understand data structure, i'm pretty sure on real hardware, std::vector kick shit out of it.

i.e. accessing memory linearly faster, cost of copying few numbers on new vector isn't bad, compared having jump , forth, possibly thrashing cpu cache if jumps larger cache line size.

hence, think practical reasons, implementation optimal, unless run out of ram.


Comments

Popular posts from this blog

Unlimited choices in BASH case statement -

Redirect to a HTTPS version using .htaccess -

javascript - jQuery: Add class depending on URL in the best way -