繁体   English   中英

我可以从基于范围的元素中移动元素吗?

[英]Can I move elements from a range-based for?

假设我有一些像这样的代码:

std::vector<std::string> produce(const std::string& str){
    // create a vector based on input
}

void consume(const std::string& str){
    for (auto i:produce(str))
        // do some thing that use the str
        // and I'd like to move it from the vector
        some_process(str) // for example, move into this function
}

我只是想知道编译器(我可以使用VS2015或gcc 6)是否可以优化以将元素移动到for循环中。 或者我该怎么做才能让它进入,因为字符串可能非常冗长。

一个老人会开始为循环或协程提供帮助吗?

如果要将元素从该向量移动到some_function()只需显式move

void some_function( std::string str );
void some_function( std::string &&str ); // or explicitly


for(auto &i:produce(str))
    some_function( std::move(i) );

否则,将元素移动到for循环中并不清​​楚你的意思。

只需auto&显示std::move

但是要花哨

struct empty_t{}; 
template<class It,class B=empty_t>struct range_t:B{
  It b,e;
  It begin()const{return b;}
  It end()const{return e;}
  range_t(It s,It f):b(std::move(s)),e(std::move(f)){}
  // fancy
  template<class S, class F>
  range_t(B base, S s, F f):B(std::move(base)),b(s(*this)),e(f(*this)){}
};
template<class It>range_t<It> range(It b, It e){return{std::move(b),std::move(e)};}
template<class B, class S, class F>
auto range( B base, S s, F f ){
  auto It=std::result_of_t<s(base)>;
  return range_t<It,B>{
    std::move(base),std::move(s),std::move(f)
  };
}
template<class R>
auto move_from(R& r){
  using std::begin; using std::end;
  return range( std::make_move_iterator(begin(r)), std::make_move_iterator(end(r)) ); 
}
template<class R>
auto move_from(R&& r){
  using std::begin; using std::end;
  return range(
    std::move(r),
    [](auto&r){return std::make_move_iterator(begin(r));},
    [](auto&r){return std::make_move_iterator(end(r));}
  ); 
}

现在,除了错别字,

for(auto i:move_from(produce(str)))
  some_function( std::move(i) );

i将成为每个元素的移动副本。

但那太疯狂了。

当您想要移动无关的迭代基于ranfe /容器的代码时,此技术可能很有用。

template<class R, class F>
auto transform_to_vector( R&& r, F&& f ){
  using std::begin; using std::end;
  using rT=std::decay_t<std::result_of_t< f(*begin(std::forward<R>(r))) >>;
  std::vector<rT> retval;
  for(auto&& e:std::forward<R>(r)){
    retval.push_back( f(decltype(e)(e)) );
  }
  return retval;
}

现在,使用move_from(x)作为“范围”调用上述内容与使用x调用它不同。 您可以想象其他算法也是这样编写的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM