C++ warning C4018: '<' : signed/unsigne

2019-01-24 01:06发布

This question already has an answer here:

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
    //...
  }
}

标签: c++ warnings
3条回答
ゆ 、 Hurt°
2楼-- · 2019-01-24 01:21

Say std::size_t i = 0;:

for (std::size_t i = 0; i != v.size(); ++i) { /* ... */ }
查看更多
Evening l夕情丶
3楼-- · 2019-01-24 01:25

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).

查看更多
在下西门庆
4楼-- · 2019-01-24 01:39

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)
{
    ...
}
查看更多
登录 后发表回答