简体   繁体   中英

Move std::unique_ptr to new position inside std::vector

I have std::vector of std::unique_ptr-s. How to move one element to another place without changing relative order of other elements?

You can use std::rotate from the <algorithm> header. If you want to move the element forward, you can use:

std::rotate(elem_iter, elem_iter + 1, elem_dest + 1);

and if you want to move it backward, you can use:

std::rotate(elem_dest, elem_iter, elem_iter + 1);

where elem_iter is an iterator pointing to the element you want to move, and elem_dest is an iterator pointing to the place you want to move it. As the name implies, std::rotate will rotate elements in a range, causing the first portion of the range to be swapped with the second. In your case, one of those portions is the element you want to move, and the other portion is all the elements between it and its destination.

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