std::vector<T>::size()
returns std::vector<T>::size_type
which is an unsigned integer type.
Consequently comparing with i
in expression i < myvec->size()
, which is of type int
(i.e., signed integer), you rightfully get a warning because you are comparing an unsigned integer with a signed one.
The reason why you get this warning is that at their extrema (i.e., their maximum and minimum values), unsigned integers can become larger than their signed counterparts. The compiler issues a warning, in order to "ask"/"warn" you if you have taken into account any issues that might come up because of this.
If this is not a problem for you, you can amend the warning by simply casting.
for(int i(0); i < static_cast<int>(myvec->size()); ++i) {
...
}
Another way would be to change the type of i
to match that of myvec->size()
:
for(std::vector<float>::size_type i(0); i < myvec->size(); ++i) {
...
}
Mind however that i
becomes an unsigned integer type and if you're decreasing it in the loop you might get unexpected results (i.e., it won't get negative values).
Another way and if your compiler supports C++11 and if you want to loop over the elements of your vector without changing the vector itself, would be to use range based loop as:
for(auto &&e : *myvec) {
...
}
My personal favourite for looping over the elements of a vector is:
for(int i(0), sz(myvec->size()); i <sz; ++i) {
...
}