【问题标题】:STL iterator resetSTL 迭代器重置
【发布时间】:2012-09-26 15:21:01
【问题描述】:

我尝试重用 STL 迭代器,但找不到任何相关信息。这段代码有问题:

    std::vector< boost::shared_ptr<Connection> >::iterator poolbegin = pool.begin();
std::vector< boost::shared_ptr<Connection> >::iterator poolend = pool.end();
if( order ) {
    poolbegin = pool.rbegin(); // Here compilation fails
    poolend   = pool.rend();
}
    for( std::vector< boost::shared_ptr<Connection> >::iterator it = poolbegin; it<poolend; it++) {

但出现错误:

错误:'poolbegin = std::vector<_tp _alloc>::rbegin() with _Tp = boost::shared_ptr, _Alloc = std::allocator >'

有没有办法将迭代器重置为新值?喜欢 shared_ptr::reset 吗?

【问题讨论】:

  • 迭代器和反向迭代器是不同的、不相关的类型。

标签: c++ stl iterator


【解决方案1】:

rbegin() 返回一个reverse_iterator,它与普通的iterator 完全不同。

它们不能相互分配。

【讨论】:

    【解决方案2】:

    看起来你想要一个循环通过一个向量向前或向后,这取决于某些条件。

    执行此操作的一种方法是将循环体分解为函子(如果您有 C++11,则为 lambda)。

    struct LoopBody {
      void operator()(boost::shared_ptr<Connection> connection) {
        // do something with the connection
      }
      // If the loop body needs to be stateful, you can add a constructor
      // that sets the initial state in member variables.
    };
    

    现在您可以有两种选择来选择您想要通过循环的方式:

    LoopBody loop_body;
    if (reverse_order) {
      std::for_each(pool.rbegin(), pool.rend(), loop_body);
    } else {
      std::for_each(pool.begin(), pool.end(), loop_body);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多