C++ 警告 C4018:“<”:有符号/无符号不匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8188401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ warning C4018: '<' : signed/unsigned mismatch
提问by ruhungry
This code throws a warnings when I compile it under windows. Any solutions?
当我在 Windows 下编译它时,这段代码会抛出警告。任何解决方案?
#include<vector>
int main(){
std::vector<int> v;
//...
for (int i = 0; i < v.size(); ++i) { //warning on this line
//...
}
}
回答by
Replace all the definitions of int i
with size_t i
.
更换的所有定义int i
用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).
std::vector<T>::size()
返回size_t
无符号的类型(因为容器包含负数的元素没有意义)。
回答by Kerrek SB
Say std::size_t i = 0;
:
说std::size_t i = 0;
:
for (std::size_t i = 0; i != v.size(); ++i) { /* ... */ }
回答by Steve Folly
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:
或者,如果您使用的是 C++11:
for (int i : v)
{
...
}