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. 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. 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. When you reach n+1 elements it may reallocate. I'd like to ask you to be more specific: what are you expecting from your code?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.