一 概述
C++ 标准库中提供了很多算法,定义于头文件 < algorithm >。本文主要探究以下用于 区间元素搬移 的算法:
std::move (C++11) 将某一范围的元素搬移到一个新的区间std::move_backward (C++11) 按从后往前的顺序搬移一个范围内的元素
二 辅助函数
三 定义
template < class InputIt , class OutputIt >
OutputIt move ( InputIt first, InputIt last, OutputIt d_first ) ;
( 1 ) ( since C++ 11 ) ( until C++ 20 )
template < class InputIt , class OutputIt >
constexpr OutputIt move ( InputIt first, InputIt last, OutputIt d_first ) ;
( 1 ) ( since C++ 20 )
template < class ExecutionPolicy , class ForwardIt1 , class ForwardIt2 >
ForwardIt2 move ( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last,
ForwardIt2 d_first ) ; ( 2 ) ( since C++ 17 )
注意:以上为< algotithm >中move的定义。我们熟悉的获取右值引用的move定义在 < utility >中,如下:
template < class T >
typename std:: remove_reference< T> :: type&& move ( T&& t ) noexcept ;
( since C++ 11 ) ( until C++ 14 )
template < class T >
constexpr typename std:: remove_reference< T> :: type&& move ( T&& t ) noexcept ; ( since C++ 14 )
template < class BidirIt1 , class BidirIt2 >
BidirIt2 move_backward ( BidirIt1 first, BidirIt1 last, BidirIt2 d_last ) ;
( since C++ 11 ) ( until C++ 20 )
template < class BidirIt1 , class BidirIt2 >
constexpr BidirIt2 move_backward ( BidirIt1 first, BidirIt1 last,
BidirIt2 d_last ) ; ( since C++ 20 )
四 Demo
if ( 1 ) {
std:: list< int > l ( 10 ) ;
std:: vector< int > vc;
fill ( vc, 1 , 9 ) ;
print ( "before move vc(src): " , vc) ;
print ( "before move list(dst): " , l) ;
std:: move ( vc. begin ( ) , vc. end ( ) , l. begin ( ) ) ;
print ( "after move vc(src): " , vc) ;
print ( "after move list(dst): " , l) ;
}
if ( 1 ) {
std:: list< std:: string> l ( 10 ) ;
std:: vector< std:: string> vc{ "hello" , "big" , "world" } ;
print1 ( "before move vc(src): " , vc) ;
print1 ( "before move list(dst): " , l) ;
std:: move ( vc. begin ( ) , vc. end ( ) , l. begin ( ) ) ;
print1 ( "after move vc(src): " , vc) ;
print1 ( "after move list(dst): " , l) ;
}
if ( 1 ) {
std:: list< int > l ( 10 ) ;
std:: vector< int > vc;
fill ( vc, 1 , 9 ) ;
print ( "before move_backward vc(src): " , vc) ;
print ( "before move_backward list(dst): " , l) ;
std:: move_backward ( vc. begin ( ) , vc. end ( ) , l. end ( ) ) ;
print ( "after move_backward vc(src): " , vc) ;
print ( "after move_backward list(dst): " , l) ;
}
before move vc ( src) : 1 2 3 4 5 6 7 8 9
before move list ( dst) : 0 0 0 0 0 0 0 0 0 0
after move vc ( src) : 1 2 3 4 5 6 7 8 9
after move list ( dst) : 1 2 3 4 5 6 7 8 9 0
before move vc ( src) : hello big world
before move list ( dst) :
after move vc ( src) :
after move list ( dst) : hello big world
before move_backward vc ( src) : 1 2 3 4 5 6 7 8 9
before move_backward list ( dst) : 0 0 0 0 0 0 0 0 0 0
after move_backward vc ( src) : 1 2 3 4 5 6 7 8 9
after move_backward list ( dst) : 0 1 2 3 4 5 6 7 8 9
五 参考