我有一个 std::vector<std::unique_ptr<object>> myObjects_ptrs
.我需要从我的一个对象开始,再次回到我开始的地方。
我是这样做的:
while(true)
{
for(int i = 0; i < myObjects_ptrs.size(); ++i)
{
myObjects_ptr[i]->doSomething();
//and here I need to circle back
for(int j = i + 1; j < myObjects_ptr.size(); ++j)
{
//do some things with each other object
}
for(int j = 0; j < i; ++j)
{
//do the same things with the rest of the objects
}
}
}
这是标准的做法吗?我的问题是,一旦我检测到某些东西,我就不需要继续四处走动了。例如,如果我在第一个循环中找到了一些东西,那么就不需要经过第二个循环。我同意通过添加额外的 if
来解决这个问题在第二个循环之前;但是有更好的方法吗?
最佳答案
您可以使用模数,即两个内部循环将变为:
int numObjects = myObjects_ptr.size();
for (int j = i + 1; j < numObjects + i + 1; ++j)
{
// Get object
auto& obj = myObjects_ptr[j % numObjects];
}
关于c++ - 如何使用 for 循环回到起点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55388771/