下面的代码片段遍历一个向量,并打印数组中当前值和上一个值之间的差异。有用。 此代码在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++;
}
如何使用
实现相同的目标答案 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;
}