26

This code throws a warnings when I compile it under windows. Any solutions?

#include<vector> 

int main(){
  std::vector<int> v;
  //...
  for (int i = 0; i < v.size(); ++i) { //warning on this line
    //...
  }
}
ruhungry
  • 4,316
  • 19
  • 53
  • 96

3 Answers3

56

Replace all the definitions of int i with size_t i.

std::vector<T>::size() returns the type size_t which is unsigned (since it doesn't make sense for containers to contain a negative number of elements).

  • 1
    This is bad idea since -3 int would be bigger then size_t 31 with your solution. While this solution works for current example, this may lead to hard to debug bugs in other cases. – Sergei Krivonos Mar 06 '17 at 09:36
8

Say std::size_t i = 0;:

for (std::size_t i = 0; i != v.size(); ++i) { /* ... */ }
Kerrek SB
  • 447,451
  • 88
  • 851
  • 1,056
7

You could also use iterators instead to avoid the potential for a warning altogether:

for (std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i)
{
    ...
}

Or if you're using C++11:

for (int i : v)
{
    ...
}
Steve Folly
  • 7,847
  • 8
  • 48
  • 59