简体   繁体   English

使用 vector.size() 的内循环导致无限循环

[英]Inner-loop using vector.size() leads to infinite loop

I am trying to avoid copying with vectors, so I am (I know -- poor practice) mutating the vector while I loop over it, but I have noticed that it evaluates size() at every loop end.我试图避免使用向量进行复制,所以我(我知道 - 糟糕的做法)在循环时改变向量,但我注意到它在每个循环结束时评估 size() 。 Furthermore, even if I declare it outside of the loop and assign it to another variable, it still reevaluates.此外,即使我在循环之外声明它并将它分配给另一个变量,它仍然会重新计算。 Even more surprising, even if I declare it const, it reevaluates.更令人惊讶的是,即使我将其声明为 const,它也会重新评估。 Can someone tell me why this is the case?有人能告诉我为什么会这样吗? And what is the best way to add to a vector without creating a separate one, then combining them after each inner loop completes?添加到向量而不创建单独的向量,然后在每个内部循环完成后组合它们的最佳方法是什么? Sample code:示例代码:

#include <vector>
int main()
{
    std::vector<int> v {0};
    // infinite loop
    for (int i = 0; i < 100; ++i)
    {
        const size_t sz = v.size();
        for (size_t j = 0; j < sz; ++j)
            v.push_back(i);
    }
    return 0;
}

I believe you are trying to avoid memory reallocation with vectors.我相信您正试图避免使用向量进行内存重新分配。 If this is the case you should use reserve(n): it preallocate memory for n elements thus avoiding memory reallocation while it have n elements or less.如果是这种情况,您应该使用 Reserve(n):它为 n 个元素预分配内存,从而避免在它有 n 个或更少元素时重新分配内存。 When you reach n+1 elements it may reallocate.当您达到 n+1 个元素时,它可能会重新分配。 I'd like to ask you to be more specific: what are you expecting from your code?我想请你更具体一点:你对你的代码有什么期望?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM