Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

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

What would be the best way to do the following?

I would like to reverse a smaller range in a vector and haven't found any better solution than this: I extract the smaller range to a newly created vector, reverse it and then add the newly created vector at the former position in the original vector.

Another way to explain what I want to do is something like 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 that order into a new vector with three element or copy element 8, 9, 10 into a new vector an reverse it. The original vector consists now of nine elements because the elements 8, 9, 10 were erased in the procedure.

2.The new vector with the 3 elements 10, 9, 8 is then copied/appended into the original vector at position 8 as a vector or element by element at position 8, 9, 10 respectively.

I am sure there are better solutions then the method mentioned above.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could in fact write an in-place swap,

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

Now, that sounds like less copying to me, but as Stroustrup himself once said:

I don't really understand your data structure, but I'm pretty sure that on real hardware, std::vector will kick the shit out of it.

I.e. accessing memory linearly is almost always faster, so the cost of copying a few numbers over to a new vector really isn't that bad, compared to having to jump back and forth, possibly thrashing your CPU cache if the jumps are larger than a cache line size.

Hence, I think for all practical reasons, your implementation is optimal, unless you run out of RAM.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...