C++ While循环不等于std::队列大小
我有以下代码:C++ While循环不等于std::队列大小,c++,while-loop,queue,C++,While Loop,Queue,我有以下代码: std::queue<unsigned int> offsets; // (fill offsets here) DEBUG(std::to_string(offsets.size())) // print offsets.size() to console int iterations = 0; while (!offsets.empty()) { iterations++; unsigned int currOffset = offsets.
std::queue<unsigned int> offsets;
// (fill offsets here)
DEBUG(std::to_string(offsets.size())) // print offsets.size() to console
int iterations = 0;
while (!offsets.empty())
{
iterations++;
unsigned int currOffset = offsets.front();
offsets.pop();
if (currOffset == 0)
{
DEBUG("breaking from while loop")
break;
}
// do something with currOffset
}
DEBUG(std::to_string(iterations))
由于某些原因,迭代永远不等于offset.size。我不知道这是为什么。在我的测试应用程序中,offset.size==28,但iterations==11。在这个应用程序中,我只中断一次while循环
知道为什么会这样吗?非常感谢您的帮助。因为第11个偏移量为零,并且条件中断会在循环到达数据结构末尾之前触发
或者//使用currOffset执行某些操作需要从队列中弹出更多内容。因为第11个偏移量为零,并且条件中断会在循环到达数据结构末尾之前触发
这或//使用currOffset执行某些操作都涉及到从队列中弹出更多内容。如果front==0,if将中断循环,不需要为空
while (!offsets.empty())
{
iterations++;
unsigned int currOffset = offsets.front();
offsets.pop();
if (currOffset == 0) // *** Here is the problem ***
{
DEBUG("breaking from while loop")
break;
}
// do something with currOffset
}
if在front==0时中断循环,不需要为空
while (!offsets.empty())
{
iterations++;
unsigned int currOffset = offsets.front();
offsets.pop();
if (currOffset == 0) // *** Here is the problem ***
{
DEBUG("breaking from while loop")
break;
}
// do something with currOffset
}
您能解释一下为什么希望迭代等于offset.size吗?因为while循环应该持续到offset.empty!=符合事实的因此,迭代应该增加每个循环,从而等于offset.size。至少我是这么想的……不,因为你在你的循环中间有一个突破。你真的要求你的环路停在中途。我不知道你为什么认为不会发生这种事。您需要在此处向我们显示填充偏移。向我们展示您的测试用例。还是我们只是在猜测@NoahRoth:那将是关键字而不是break。你能解释一下为什么你希望迭代等于offset.size吗?因为while循环应该持续到offset.empty!=符合事实的因此,迭代应该增加每个循环,从而等于offset.size。至少我是这么想的……不,因为你在你的循环中间有一个突破。你真的要求你的环路停在中途。我不知道你为什么认为不会发生这种事。您需要在此处向我们显示填充偏移。向我们展示您的测试用例。还是我们只是在猜测@诺阿罗斯:那将是关键词,而不是break。