函式模板
<algorithm>

std::move

template <class InputIterator, class OutputIterator>  OutputIterator move (InputIterator first, InputIterator last, OutputIterator result);
移動元素範圍
將範圍 [first,last) 中的元素移動到以 result 開頭的範圍。

元素的值從範圍 [first,last) 轉移到 result 指向的元素。呼叫後,範圍 [first,last) 中的元素將處於一個未指定但有效的狀態。

範圍的重疊方式不應使得 result 指向範圍 [first,last) 中的元素。對於此類情況,請參見 move_backward

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
template<class InputIterator, class OutputIterator>
  OutputIterator move (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = std::move(*first);
    ++result; ++first;
  }
  return result;
}

引數

first, last
輸入迭代器,指向要移動的序列的初始位置和最終位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
result
輸出迭代器,指向目標序列的初始位置。
此迭代器不應指向範圍 [first,last) 中的任何元素。

返回值

指向目標範圍的結束的迭代器,其中元素已被移動。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// move algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::move (ranges)
#include <utility>      // std::move (objects)
#include <vector>       // std::vector
#include <string>       // std::string

int main () {
  std::vector<std::string> foo = {"air","water","fire","earth"};
  std::vector<std::string> bar (4);

  // moving ranges:
  std::cout << "Moving ranges...\n";
  std::move ( foo.begin(), foo.begin()+4, bar.begin() );

  std::cout << "foo contains " << foo.size() << " elements:";
  std::cout << " (each in an unspecified but valid state)";
  std::cout << '\n';

  std::cout << "bar contains " << bar.size() << " elements:";
  for (std::string& x: bar) std::cout << " [" << x << "]";
  std::cout << '\n';

  // moving container:
  std::cout << "Moving container...\n";
  foo = std::move (bar);

  std::cout << "foo contains " << foo.size() << " elements:";
  for (std::string& x: foo) std::cout << " [" << x << "]";
  std::cout << '\n';

  std::cout << "bar is in an unspecified but valid state";
  std::cout << '\n';

  return 0;
}

可能的輸出
Moving ranges...
foo contains 4 elements: (each in an unspecified but valid state)
bar contains 4 elements: [air] [water] [fire] [earth]
Moving container...
foo contains 4 elements: [air] [water] [fire] [earth]
bar is in an unspecified but valid state


複雜度

線性複雜度,複雜度為 firstlast 之間 距離的線性複雜度:對範圍中的每個元素執行移動賦值。

資料競爭

兩個範圍內的物件都會被修改。

異常

如果元素移動賦值或迭代器上的操作丟擲異常,則此函式也會丟擲異常。
請注意,無效引數會導致未定義行為

另見