
(screenshot from http://www.cplusplus.com/reference/vector/vector/size/)
therefore
assert (vec.size() > -1);
will always fail, since -1 is upgraded to unsigned int type in implicit conversion during comparision and becomes the largest unsigned int.
Suggestion: when checking error input, use closed conditions instead of open conditions, which are common to iteration termination.
i.e.
assert(vec.size() >= 0);
and
for large container use:
unsigned int nSize = vec.size(); //since int and unsigned are of the same length and the size cannot be negative. int nSize can give correct comparision result to other int, but negative region is rather pointless.
Be aware!

本文探讨了C++中检查vector容器大小时可能出现的问题,特别是使用负数进行比较的情况。建议采用闭合条件而非开放条件,并提供了解决方案。
193

被折叠的 条评论
为什么被折叠?



