简体   繁体   中英

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 .

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

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).

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. 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( 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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