C ++反转向量中的较小范围 [英] 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.
我想做的是这样的:
原始向量:1 2 3 4 5 6 7 8 9 10 11。
Original vector: 1 2 3 4 5 6 7 8 9 10 11.
希望的结果:1 2 3 4 5 6 7 10 9 8 11。
Wanted result: 1 2 3 4 5 6 7 10 9 8 11.
- 按顺序复制10,9,8转换成具有三个元素或复制元素8,9,10的新向量到新向量中。原始向量现在由九个元素组成,因为元素8,9,10在过程中被删除。
随后将3个元素10,9,8作为向量或分别在位置8,9,10处的元素复制/附加到位置8处的原始向量中。
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.
推荐答案
你可以写一个就地交换,
You could in fact write an in-place swap,
- 取得最后一个索引和第一个交换索引,
- li>
- 减少最后一个索引并增加第一个索引
- 并重复,直到
last_index - 1 <= first_index
。
- 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
.
现在,这听起来好像没有复制给我,但Stroustrup自己曾经说过:
Now, that sounds like less copying to me, but as Stroustrup himself once said:
我真的不理解你的数据结构,但我很确定在真实的硬件上,
std :: vector
将会踢掉它。
访问内存的线性几乎总是更快,因此将复制几个数字到一个新的向量的成本真的不是那么糟糕,与必须来回跳跃,如果跳跃大于一个缓存,可能颠簸你的CPU缓存
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.
这篇关于C ++反转向量中的较小范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!