What is the most effective way to move items within a vector?

前端 未结 3 1320
别跟我提以往
别跟我提以往 2020-12-29 05:46

I\'ve seen some special cases where std::rotate could be used or a combination with one of the search algorithms but generally: when one has a vector of N items

3条回答
  •  时光说笑
    2020-12-29 06:29

    Pre-C++11 (although the following remains valid) you can get more efficient "moves" for contained types which specialise/overload std::swap. To take advantage of this, you would need to do something like

    std::vector new_vec;
    Foo tmp;
    
    for (/* each Foo&f in old_vec, first section */) {
        swap (f, tmp);
        new_vec .push_back (tmp);
    }
    
    for (/* each Foo&f in old_vec, second section */) {
        swap (f, tmp);
        new_vec .push_back (tmp);
    }
    
    for (/* each Foo&f in old_vec, third section */) {
        swap (f, tmp);
        new_vec .push_back (tmp);
    }
    
    swap (new_vec, old_vec);
    

    The above may also give good results for C++11 if Foo has a move-operator but hasn't specialised swap.

    Linked lists or some clever sequence type might work out better if Foo doesn't have move semantics or an otherwise-optimised swap

    Note also that if the above is in a function

    std::vector move (std::vector old_vec, ...)`
    

    then you might be able to perform the whole operation without copying anything, even in C++98 but for this to work you will need to pass by value and not by reference, which goes against the conventional prefer-pass-by-reference wisdom.

提交回复
热议问题