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


C++ move()用法及代碼示例

C++ 算法 move()function 用於移動元素。它接受三個參數,然後將屬於範圍 [first,last) 的元素移動到以 'result' 開頭的範圍中。

用法

template<class InputIterator, class OutputIterator> OutputIterator move(InputIterator first, InputIterator last, OutputIterator result);

參數

first:它是範圍​​的第一個元素的輸入迭代器,其中元素本身包含在範圍內。

last: 它是範圍最後一個元素的輸入迭代器,其中元素本身不包含在範圍內。

result:它是移動元素初始位置的輸出迭代器。

返回值

該函數將第一個元素的迭代器返回到移動的元素序列。

例子1

#include <iostream>     
#include <algorithm>    
#include <utility>      
#include <vector>       
#include <string>       
int main () 
{
  std::vector<std::string> a = {"suraj","aman","vanshika","chhavi"};
  std::vector<std::string> b (4);
  std::cout << "Move function.\n";
  std::move ( a.begin(), a.begin()+4, b.begin() );
  std::cout << "a contains " << a.size() << " elements:";
  std::cout << " (The state of which is valid.)";
  std::cout << '\n';
  std::cout << "b contains " << b.size() << " elements:";
  for (std::string& x:b) std::cout << " [" << x << "]";
  std::cout << '\n';
  std::cout << "Moving the conatiner a...\n";
  a = std::move (b);
  std::cout << "a contains " << a.size() << " elements:";
  for (std::string& x:a) std::cout << " [" << x << "]";
  std::cout << '\n';
  std::cout << "b is in valid state";
  std::cout << '\n';
  return 0;
}

輸出:

Move function.
a contains 4 elements:(The state of which is valid.)
b contains 4 elements:[suraj] [aman] [vanshika] [chhavi]
Moving the conatiner a...
a contains 4 elements:[suraj] [aman] [vanshika] [chhavi]
b is in valid state

例子2

#include<bits/stdc++.h>
int main()
{
    std::vector <int> u1 {9, 14, 21, 18};
    std::vector <int> u2 {14, 14, 14, 14};
    std::cout << "u1 contains:";
    for(int j = 0; j < u1.size(); j++)
        std::cout << " " << u1[j];
    std::cout << "\n";
    std::cout << "u2 contains:";
    for(unsigned int j = 0; j < u2.size(); j++)
        std::cout << " " << u2[j];
    std::cout << "\n\n";
    std::move (u1.begin(), u1.begin() + 4, u2.begin() + 1);
    std::cout << "u2 contains after move function:";
    for(unsigned int j = 0; j < u2.size(); j++)
        std::cout << " " << u2[j];
    std::cout << "\n";
    return 0;
}

輸出:

u1 contains:9 14 21 18
u2 contains:14 14 14 14

u2 contains after move function:14 9 14 21

複雜度

函數的複雜度從第一個元素到最後一個元素是線性的。

數據競爭

訪問部分或全部容器對象。

異常

如果任何容器元素拋出一個異常,該函數就會拋出異常。






相關用法


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