最終更新日時(UTC):
が更新

履歴 編集

function template
<algorithm>

std::ranges::move(C++20)

namespace std::ranges {
  template <input_iterator I,
            sentinel_for<I> S,
            weakly_incrementable O>
    requires indirectly_movable<I, O>
  constexpr move_result<I, O>
    move(I first,
         S last,
         O result);           // (1) C++20

  template <input_range R,
            weakly_incrementable O>
    requires indirectly_movable<iterator_t<R>, O>
  constexpr move_result<borrowed_iterator_t<R>, O>
    move(R&& r,
         O result);           // (2) C++20

  template <execution-policy Ep,
            random_access_iterator I,
            sized_sentinel_for<I> S,
            random_access_iterator O,
            sized_sentinel_for<O> OutS>
    requires indirectly_movable<I, O>
  move_result<I, O>
    move(Ep&& exec,
         I first,
         S last,
         O result,
         OutS result_last);   // (3) C++26

  template <execution-policy Ep,
            sized-random-access-range R,
            sized-random-access-range OutR>
    requires indirectly_movable<iterator_t<R>, iterator_t<OutR>>
  move_result<borrowed_iterator_t<R>, borrowed_iterator_t<OutR>>
    move(Ep&& exec,
         R&& r,
         OutR&& result_r);    // (4) C++26
}

概要

指定された範囲の要素をムーブする。

  • (1): イテレータ範囲を指定する
  • (2): Rangeを直接指定する
  • (3): (1)の並列アルゴリズム版。実行ポリシーを指定し、出力範囲の終端も指定する
  • (4): (2)の並列アルゴリズム版。実行ポリシーを指定する

事前条件

result[first,last) の範囲に含まれてはならない。

効果

[first,last) 内の要素を、それぞれ [result,result + (last - first)) へムーブする。

ムーブは first から順番に行い、0 以上 last - first 未満であるそれぞれの n について、*(result + n) = std::move(*(first + n)) を行う。

戻り値

move_result {
  .in  = last,
  .out = result + (last - first),
}

計算量

正確に last - first 回ムーブ代入が行われる。

基本的な使い方

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <memory>

int main() {
  std::vector<std::unique_ptr<int>> v;
  for (int i = 0; i < 5; i++) {
    v.emplace_back(new int(i));
  }

  std::vector<std::unique_ptr<int>> v2;
  // v のそれぞれの要素を v2 へムーブする
  std::ranges::move(v, std::back_inserter(v2));

  for (const auto& v : v2) {
    std::cout << *v << std::endl;
  }
}

出力

0
1
2
3
4

並列アルゴリズムの例 (C++26)

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <execution>

int main() {
  std::vector<std::string> src = {"hello", "world", "foo", "bar", "baz"};
  std::vector<std::string> dst(src.size());

  // 並列にムーブする
  std::ranges::move(std::execution::par, src, dst);

  for (const auto& s : dst) {
    std::cout << s << ' ';
  }
  std::cout << std::endl;
}

出力

hello world foo bar baz

バージョン

言語

  • C++20

処理系

参照