Iterating over std::vector: unsigned vs signed index — which to choose?
Hello everyone! I recently started learning C++ and encountered a problem when iterating over `std::vector`. When I write a loop, I usually use `int i`, but the compiler (GCC) gives a warning about comparing signed and unsigned. Here's an example:
```cpp
#include
#include
int main() {
std::vector vec = {1, 2, 3, 4, 5};
for (int i = 0; i < vec.size(); ++i) { // warning: comparison between signed and unsigned integer expressions
std::cout << vec[i] << " ";
}
return 0;
}
```
Warning: `warning: comparison between signed and unsigned integer expressions [-Wsign-compare]`.
I understand that `vec.size()` returns `size_t` (unsigned), while my `i` is `int` (signed). If I change `int` to `size_t` or `unsigned int`, the warning disappears. But then I can't use `i >= 0` in reverse loops, because `size_t` is never negative, and the loop becomes infinite.
Question: which type is better to use for the index when iterating over a vector? Should
No answers yet.
Log in to leave an answer