Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::ranges::to

      From cppreference.com
      <cpp‎ |ranges
       
       
      Ranges library
      Range adaptors
       
      Defined in header<ranges>
      template<class C,ranges::input_range R,class...Args>

          requires(!ranges::view<C>)

      constexpr C to( R&& r, Args&&...args);
      (1)(since C++23)
      template<template<class...>class C,

               ranges::input_range R,class...Args>

      constexprauto to( R&& r, Args&&...args);
      (2)(since C++23)
      template<class C,class...Args>

          requires(!ranges::view<C>)

      constexpr/*range adaptor closure*/ to( Args&&...args);
      (3)(since C++23)
      template<template<class...>class C,class...Args>
      constexpr/*range adaptor closure*/ to( Args&&...args);
      (4)(since C++23)
      Helper templates
      template<class Container>

      constexprbool/*reservable-container*/=
         ranges::sized_range<Container>&&
          requires(Container& c,ranges::range_size_t<Container> n)
         {
              c.reserve(n);
             { c.capacity()}->std::same_as<decltype(n)>;
             { c.max_size()}->std::same_as<decltype(n)>;

         };
      (5)(exposition only*)
      template<class Container,class Reference>

      constexprbool/*container-appendable*/=
          requires(Container& c, Reference&& ref)
         {
              requires
             (
                  requires{ c.emplace_back(std::forward<Reference>(ref));}    ||
                  requires{ c.push_back(std::forward<Reference>(ref));}        ||
                  requires{ c.emplace(c.end(),std::forward<Reference>(ref));}||
                  requires{ c.insert(c.end(),std::forward<Reference>(ref));}
             );

         };
      (6)(exposition only*)
      template<class Reference,class C>
      constexprauto/*container-appender*/( C& c);
      (7)(exposition only*)
      template<class R,class T>

      concept/*container-compatible-range*/=
         ranges::input_range<R>&&

         std::convertible_to<ranges::range_reference_t<R>, T>;
      (8)(exposition only*)

      The overloads of the range conversion function construct a new non-view object from a source range as its first argument by calling a constructor taking a range, astd::from_range_t tagged ranged constructor, a constructor taking an iterator-sentinel pair, or by back inserting each element of the source range into the arguments-constructed object.

      1) Constructs an object of typeC from the elements ofr in the following:
      a) IfC does not satisfyinput_range orstd::convertible_to<ranges::range_reference_t<R>,ranges::range_value_t<C>> istrue:
      1) Constructing a non-view object as ifdirect-initializing (but not direct-list-initializing) an object of typeC from the source rangestd::forward<R>(r) and the rest of the functional argumentsstd::forward<Args>(args)... ifstd::constructible_from<C, R, Args...> istrue.
      2) Otherwise, constructing a non-view object as ifdirect-initializing (but not direct-list-initializing) an object of typeC from additional disambiguation tagstd::from_range, the source rangestd::forward<R>(r) and the rest of the functional argumentsstd::forward<Args>(args)... ifstd::constructible_from<C,std::from_range_t, R, Args...> istrue.
      3) Otherwise, constructing a non-view object as ifdirect-initializing (but not direct-list-initializing) an object of typeC from the iterator-sentinel pair (ranges::begin(r) as an iterator andranges::end(r) as sentinel, where iterator and sentinel have the same type. In other words, the source range must be a common range), and the rest of function argumentsstd::forward<Args>(args)... if all of the conditions below aretrue:
      4) Otherwise, constructing a non-view range object as ifdirect-initializing (but not direct-list-initializing) an object of typeC from the rest of the function argumentsstd::forward<Args>(args)... with the following equivalent call below after the construction:

      ifconstexpr(ranges::sized_range<R>&&/*reservable-container*/<C>)
          c.reserve(static_cast<ranges::range_size_t<C>>(ranges::size(r)));
      ranges::for_each(r,/*container-appender*/(c));

      (until C++26)

      ifconstexpr(ranges::approximately_sized_range<R>
                 &&/*reservable-container*/<C>)
          c.reserve(static_cast<ranges::range_size_t<C>>(ranges::reserve_hint(r)));
      ranges::for_each(r,/*container-appender*/(c));

      (since C++26)

      If theR satisfiessized_range(until C++26)approximately_sized_range(since C++26) andC satisfiesreservable-container, the constructed objectc of typeC is able to reserve storage with the initial storage sizeranges::size(r)(until C++26)ranges::reserve_hint(r)(since C++26) to prevent additional allocations during inserting new elements. Each element ofr is appended toc.

      The operations above are valid if both of the conditions below aretrue:

      b) Otherwise, the return expression is equivalent to:

      to<C>(ranges::ref_view(r)|views::transform([](auto&& elem)
      {
         return to<ranges::range_value_t<C>>(std::forward<decltype(elem)>(elem));
      }),std::forward<Args>(args)...)

      Which allows nested range constructions within the range ifranges::input_range<ranges::range_reference_t<C>> istrue.

      Otherwise, the program is ill-formed.
      2) Constructs an object of deduced type from the elements ofr.

      Let/*input-iterator*/ be an exposition only type that satisfiesLegacyInputIterator:

      struct/*input-iterator*/

      {
         using iterator_category=std::input_iterator_tag;
         using value_type=ranges::range_value_t<R>;
         using difference_type=std::ptrdiff_t;
         using pointer=std::add_pointer_t<ranges::range_reference_t<R>>;
         using reference=ranges::range_reference_t<R>;
          reference operator*()const;                      // not defined
          pointer operator->()const;                      // not defined
         /*input-iterator*/& operator++();                // not defined
         /*input-iterator*/ operator++(int);              // not defined
         bool operator==(const/*input-iterator*/&)const;// not defined

      };
      (exposition only*)

      Let/*DEDUCE-EXPR*/ be defined as follows:

      The call is equivalent toto<decltype(/*DEDUCE-EXPR*/)>
         (std::forward<R>(r),std::forward<Args>(args)...)
      .
      3,4) Returns a perfect forwarding call wrapper that is also aRangeAdaptorClosureObject.
      5) Istrue if it satisfiesranges::sized_range and is eligible to be reservable.
      6) Istrue if one element of typeReference can be appended toContainer through a member function callemplace_back,push_back,emplace orinsert.
      7) Returns a function object where a call to the returned function object is expression-equivalent to appending one element to a container. The return expression is equivalent to:

      return[&c]<class Reference>(Reference&& ref)
      {
         ifconstexpr(requires{ c.emplace_back(std::declval<Reference>());})
              c.emplace_back(std::forward<Reference>(ref));
         elseifconstexpr(requires{ c.push_back(std::declval<Reference>());})
              c.push_back(std::forward<Reference>(ref));
         elseifconstexpr(requires{ c.emplace(c.end(),
                                                 std::declval<Reference>());})
              c.emplace(c.end(),std::forward<Reference>(ref));
         else
              c.insert(c.end(),std::forward<Reference>(ref));
      };

      8) Is used in the definition of containers in constructing an input rangeR whose range reference type must be convertible toT.

      Contents

      [edit]Parameters

      r - a source range object
      args - list of the arguments to(1,2) construct a range or(3,4) bind to the last parameters of range adaptor closure object
      Type requirements
      -
      C must be cv-unqualified class type(1,3)

      [edit]Return value

      1,2) A constructed non-view object.
      3,4) A range adaptor closure object of unspecified type, with the following properties:

      ranges::to return type

      Member objects

      The returned object behaves as if it has no target object, and anstd::tuple objecttup constructed withstd::tuple<std::decay_t<Args>...>(std::forward<Args>(args)...), except that the returned object's assignment behavior is unspecified and the names are for exposition only.

      Constructors

      The return type ofranges::to(3,4) behaves as if its copy/move constructors perform a memberwise copy/move. It isCopyConstructible if all of its member objects (specified above) areCopyConstructible, and isMoveConstructible otherwise.

      Member functionoperator()

      Given an objectG obtained from an earlier call torange::to</* see below */>(args...), when a glvalueg designatingG is invoked in a function call expressiong(r), an invocation of the stored object takes place, as if by

      • ranges::to</* see below */>(r, std::get<Ns>(g.tup)...), where
      • r is a source range object that must satisfyinput_range.
      • Ns is an integer pack0,1, ...,(sizeof...(Args)-1).
      • g is an lvalue in the call expression if it is an lvalue in the call expression, and is an rvalue otherwise. Thusstd::move(g)(r) can move the bound arguments into the call, whereg(r) would copy.
      • The specified template argument is(3)C or(4) the deduced type from a class templateC that must not satisfyview.

      The program is ill-formed ifg has volatile-qualified type.

      [edit]Exceptions

      Only throws if construction of a non-view object throws.

      [edit]Notes

      The insertion of elements into the container may involve copy which can be less efficient than move because lvalue references are produced during the indirection call. Users can opt-in to useviews::as_rvalue to adapt the range in order for their elements to always produce an rvalue reference during the indirection call which implies move.

      The parentheses are mandatory when using the pipe syntax.

      auto vec= r| std::ranges::to<std::vector>;// Errorauto vec= r| std::ranges::to<std::vector>();// OK
      Feature-test macroValueStdFeature
      __cpp_lib_ranges_to_container202202L(C++23)std::ranges::to
      __cpp_lib_ranges_reserve_hint202502L(C++26)ranges::approximately_sized_range,ranges::reserve_hint, andchanges tostd::ranges::to

      [edit]Example

      A preview link:Compiler Explorer

      Run this code
      #include <boost/container/devector.hpp>#include <concepts>#include <initializer_list>#include <list>#include <print>#include <ranges>#include <regex>#include <string>#include <vector> #ifndef __cpp_lib_format_ranges#include <format>#include <sstream> auto print_aid(constauto& v){std::ostringstream out;    out<<'[';for(int n{};constauto& e: v)        out<<(n++?", ":"")<< e;    out<<']';return out;} template<typename T>structstd::formatter<std::vector<T>,char>{template<class ParseContext>constexpr ParseContext::iterator parse(ParseContext& ctx){return ctx.begin();} template<class FmtContext>    FmtContext::iterator format(autoconst& s, FmtContext& ctx)const{auto out{print_aid(s)};return std::ranges::copy(std::move(out).str(), ctx.out()).out;}}; template<typename T>structstd::formatter<std::list<T>,char>{template<class ParseContext>constexpr ParseContext::iterator parse(ParseContext& ctx){return ctx.begin();} template<class FmtContext>    FmtContext::iterator format(autoconst& s, FmtContext& ctx)const{auto out{print_aid(s)};return std::ranges::copy(std::move(out).str(), ctx.out()).out;}};#endif int main(){auto vec= std::views::iota(1,5)| std::views::transform([](int v){return v*2;})| std::ranges::to<std::vector>();     static_assert(std::same_as<decltype(vec),std::vector<int>>);std::println("{}", vec); auto list= vec| std::views::take(3)| std::ranges::to<std::list<double>>();std::println("{}", list);} void ctor_demos(){// 1.a.1) Direct init{char array[]{'a','b','\0','c'}; // Argument type is convertible to result value type:auto str_to= std::ranges::to<std::string>(array);// Equivalent tostd::string str(array); // Result type is not an input range:auto re_to= std::ranges::to<std::regex>(array);// Equivalent tostd::regex re(array);} // 1.a.2) from_range ctor{auto list={'a','b','\0','c'}; // Argument type is convertible to result value type:auto str_to= std::ranges::to<std::string>(list);// Equivalent to// std::string str(std::from_range, list); // Result type is not an input range:[[maybe_unused]]auto pair_to= std::ranges::to<std::pair<std::from_range_t,bool>>(true);// Equivalent tostd::pair<std::from_range_t,bool> pair(std::from_range,true);} // 1.a.3) iterator pair ctor{auto list={'a','b','\0','c'}; // Argument type is convertible to result value type:auto devector_to= std::ranges::to<boost::container::devector<char>>(list);// Equivalent to        boost::container::devector<char> devector(std::ranges::begin(list),                                                  std::ranges::end(list)); // Result type is not an input range:std::regex re;auto it_to= std::ranges::to<std::cregex_iterator>(list, re);// Equivalent tostd::cregex_iterator it(std::ranges::begin(list), std::ranges::end(list), re);}}

      Output:

      [2, 4, 6, 8][2, 4, 6]

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 3984C++23the nested construction branch ofranges::to resulted to
      program ill-formed ifR& does not modelviewable_range
      made well-formed
      LWG 4016C++23the container insertion branch of
      ranges::to involved use of insert iterators
      replaced with direct appending
      of elements to container

      [edit]References

      • C++23 standard (ISO/IEC 14882:2024):
      • 26.5.7 Range conversions [range.utility.conv]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/to&oldid=182457"

      [8]ページ先頭

      ©2009-2025 Movatter.jp