简体   繁体   English

将元素从向量A反向移动到向量B(不为空)

[英]Move element from vector A to vector B (not empty) in reverse order

I need to push all elements from vector bacward_segment in reverse order into forward_segment . 我需要将向量bacward_segment中的所有元素按相反顺序推入forward_segment

This is my code: 这是我的代码:

for(int q = backward_segment.size()-1; q >= 0; q--){
                forward_segment.push_back(backward_segment[q]);
        }

But I think is not so efficient.. Can you suggest to me a better solution? 但是我认为效率不高。您能建议我一个更好的解决方案吗?

If copy is enough 如果复制足够

If you're initializing forward_segment it's as simple as 如果您要初始化forward_segment它就像

vector<T> forward_segment(backward_segment.crbegin(), backward_segment.crend());

otherwise: 除此以外:

forward_segment.resize(backward_segment.size());
copy(backward_segment.crbegin(), backward_segment.crend(), forward_segment.begin());

If you actually need to move elements 如果您确实需要移动元素

Use make_move_iterator (note that I'm not using const iterators for this). 使用make_move_iterator (请注意,我没有为此使用const迭代器)。

Initialization: 初始化:

vector<T> forward_segment(
    make_move_iterator(backward_segment.rbegin()),
    make_move_iterator(backward_segment.rend())
);

otherwise: 除此以外:

forward_segment.resize(backward_segment.size());
copy(
    make_move_iterator(backward_segment.rbegin()),
    make_move_iterator(backward_segment.rend()),
    forward_segment.begin()
);

But I think is not so efficient.. 但我认为效率不高。

You should not "think" about that. 您不应该对此“思考”。 Use profiler instead. 请改用探查器。 Optimization by guessing almost never works. 通过猜测进行优化几乎是行不通的。

Can you suggest to me a better solution? 您能建议我一个更好的解决方案吗?

You can reserve size of forward_segment to backward_segment 's size if you expect not too many duplicates would be skipped. 你可以保留的大小forward_segmentbackward_segment如果你希望不会有太多的重复会被跳过的规模。 Better optimization could be done on algorithm level, for example skipping whole copy at all, but you do not provide enough information for that. 可以在算法级别上进行更好的优化,例如完全跳过整个副本,但是您没有为此提供足够的信息。

You can use std::unique_copy : 您可以使用std::unique_copy

std::unique_copy( backward_segment.rbegin(), backward_segment.rend(),
                  std::back_inserter( forward_segment ),
                  []( const auto &s1, const auto &s2 ) {
                       return s1.x == s2.x && s1.y == s2.y;
                  } );

it would make it more readable (in my opinion), but compexity would be pretty much the same. (我认为)这将使其更具可读性,但是兼容性几乎相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM