使用循环队列和迭代器自动换行

时间:2018-01-12 09:00:21

标签: c++

下面的代码片段遍历一个向量,并打印数组中当前值和上一个值之间的差异。有用。 此代码在infinte for循环中循环

    start = 60;
    iterator = 0;
    std::vector<ushort> m_xPos(600,0); // consists of 600 elements with default 0.

    for ( ;; ) {
        //If we are at the end of the path vector, we need to reset our iterators
        if ( start+iterator) >= m_xPos.size() ) {
            start = 0;
            iterator = 0;
            std::cout << m_xPos.at(0) - m_xPos.at(m_xPos.size() - 1);
        } 
        else {
            std::cout <<  m_xPos.at(start+iterator) - m_xPos.at(start+iterator-(ushort)1);
        }
        iterator++;

    }

如何使用

实现相同的目标
  1. 的std :: VEC:迭代?
  2. 循环队列?
  3. 还有其他更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

当迭代器到达m_xPos.begin()

时,您只需要指定m_xPos.end()的内容
auto circularNext = [&m_xPos](auto it) { ++it; return (it == m_xPos.end()) ? m_xPos.begin() : it; };
for (auto first = m_xPos.begin() + 59, second = m_xPos.begin() + 60; ; first = circularNext(first), second = circularNext(second)) {
    std::cout << *second - *first;
}