當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ std::move_backward用法及代碼示例


從末尾開始將[first,last]範圍內的元素移到終止於結果的範圍內。
該函數首先將*(last-1)移至*(result-1),然後向後跟隨這些元素之前的元素,直到到達第一個元素(並包括它)。
模板:

BidirectionalIterator2 move_backward (BidirectionalIterator1 first,
                                      BidirectionalIterator1 last,
                                      BidirectionalIterator2 result);

result
Bidirectional iterator to the past-the-end position in the destination sequence.
This shall not point to any element in the range [first,last].

返回類型:
An iterator to the first element of the destination sequence where elements
have been moved.

例子:

Input:
vec1 contains:3 4 5 7 8
vec2 contains:8 9 6 2 4 7
Output:
arr2 contains:8 9 6 5 7 8
/*3 elements from 3rd position of vector vec1 moved to starting 4th position of vec2*/
// CPP program to illustrate 
// std::move and std::move_backward 
// STL library functions 
#include<bits/stdc++.h> 
  
// Driver code 
int main() 
{ 
    std::vector <int> vec1 {1, 2, 3, 4, 5}; 
    std::vector <int> vec2 {7, 7, 7, 7, 7}; 
  
    // Print elements 
    std::cout << "Vector1 contains:"; 
    for(int i = 0; i < vec1.size(); i++) 
        std::cout << " " << vec1[i]; 
    std::cout << "\n"; 
      
    // Print elements 
    std::cout << "Vector2 contains:"; 
    for(unsigned int i = 0; i < vec2.size(); i++) 
        std::cout << " " << vec2[i]; 
    std::cout << "\n\n"; 
      
  
    // std::move_backward function 
    std::move_backward (vec2.begin(), vec2.begin() + 3, vec1.begin() + 3); 
  
    // Print elements 
    std::cout << "Vector1 contains after std::move_backward function:"; 
    for(unsigned int i = 0; i < vec1.size(); i++) 
        std::cout << " " << vec1[i]; 
    std::cout << "\n"; 
  
    return 0; 
}

輸出:


Vector1 contains:1 2 3 4 5
Vector2 contains:7 7 7 7 7

Vector1 contains after std::move_backward function:7 7 7 4 5


相關用法


注:本文由純淨天空篩選整理自 std::move_backward in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。