非单元迭代器步长与非随机存取迭代器 [英] Non-unit iterator stride with non-random access iterators

查看:255
本文介绍了非单元迭代器步长与非随机存取迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用随机存取迭代器,您可以通过简单地执行iter + = n然后使用< container.end()而不是!= container.end()作为循环结束条件:

With a random access iterator, you can change the stride length by simply doing iter+=n and then using < container.end() instead of != container.end() as the loop ending condition:

#include <iostream>
#include <vector>

int main(int argc, char *argv[])
{
  typedef std::vector<float> VectorType;
  typedef VectorType::const_iterator IteratorType;

  VectorType v;
  for(unsigned int i = 0; i < 11; ++i)
  {
    v.push_back(i);
  }

  for(IteratorType iter = v.begin(); iter < v.end(); iter += 2)
  {
    std::cout << " " << *iter;
  }

  return 0;
}

但是,+ = 2和& iter.end()似乎是未定义的像std :: set。似乎合理的想要遍历一个集合只访问每个其他元素(subsampling it),没有?有没有其他方法可以做到这一点?

However both += 2 and < iter.end() seem to be undefined for something like std::set. It seems reasonable to want traverse a set only visiting every other element (subsampling it), no? Is there another way to do this?

推荐答案


使用随机访问迭代器,通过简单地做 iter + = n 然后使用< container.end()而不是!= container.end()作为循环结束条件

With a random access iterator, you can change the stride length by simply doing iter+=n and then using < container.end() instead of != container.end() as the loop ending condition

其实,你不能。虽然代码可以编译,但如果迭代器实际上超过了容器的末尾,它在运行时会显示未定义的行为。

Actually, you cannot. While the code may compile, it exhibits undefined behavior at runtime if the iterator is actually advanced past the end of the container. You cannot increment an iterator beyond the end of the range into which it points.

无论如何,你可以写一个函数模板来帮助:

In any case, you can write a function template to help:

template <typename TForwardIt, typename TDifference>
bool try_advance(TForwardIt& it,
                 TForwardIt const end,
                 TDifference n)
{
    TDifference i(0);
    while (i < n && it != end)
    {
        ++i;
        ++it;
    }

    return i == n;
}

这篇关于非单元迭代器步长与非随机存取迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆