Why is there a warning with -Wsign-compare
?
As the name of the warning, and its text, imply, the issue is that you are comparing a signed and an unsigned integer. It is generally assumed that this is an accident.
In order to avoid this warning, you simply need to ensure that both operands of <
(or any other comparison operator) are either both signed or both unsigned.
How could I do better ?
The idiomatic way of writing a for
loop is to initialize both the counter and the limit in the first statement:
for (std::size_t i = 0, max = vec.size(); i != max; ++i)
This saves recomputing size()
at each iteration.
You could also (and probably should) use iterators instead of indices:
for (auto it = vec.begin(), end = vec.end(); it != end; ++it)
auto
here is a shorthand for std::vector<int>::iterator
. Iterators work for any kind of containers, whereas indices limit you to C-arrays, deque
and vector
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…