错误C4018与向量大小()在c ++ [英] error C4018 with vector size() in c++
问题描述
当我在c ++中使用带有向量的函数.size()时会收到警告
存储一个示例代码:
im getting a warning when i use the function .size() with vectors in c++ Heres a sample code:
vector<classname*> object;
object.push_back(new classname2);
for(int i=0;i<object.size();i++){
....}
我收到警告:
警告C4018:'<':signed / unsigned mismatch
warning C4018: '<' : signed/unsigned mismatch
我不允许在我的最终代码中有任何错误或警告,所以我需要摆脱这个/找到一种替代方法,我该如何摆脱这一点?
I'm not allowed to have any errors or warnings in my final code so i need to get rid of this/find an alternative method, how can i get rid of this?
推荐答案
问题是,当处理签名到无符号的比较时,会有一个潜在的。如果你在32位机器上签名的 int
是4字节,那么向量的大小可能超过该类型可表示的最大数量。
The problem is that there is a potential (breaking) issue that one can incur when dealing with signed-to-unsigned comparisons. If you're on a 32-bit machine where a signed int
is 4 bytes, it could be possible that the size of the vector could exceed the maximum quantity representable by that type. When that happens, you get signed overflow and consequentially Undefined Behavior.
以下是您可以使用的几种替代方法:
Here are a few alternatives you can uses:
for (std::vector<classname>::size_type i = 0; i < object.size(); ++i);
这保证是正确的,因为它是 code>返回。
This is guaranteed to be correct as it is the type the size
returns.
std::vector<classname>::iterator it;
for (it = object.begin(); it != object.end(); ++it);
C ++ 11:基于范围的:
C++11: Range-based for:
for (auto& a : object)
{
// ...
}
$ b b
std :: size_t
:
std::size_t
:
for (std::size_t i = 0; i < object.size(); ++i);
如doomster在注释中所说, std :: size_t
很可能具有您的底层平台的位元大小。
As doomster said in the comments, std::size_t
is likely to have the bit-size of your underlying platform.
for (unsigned int i = 0; i < object.size(); ++i);
注意:使用这个,你假设
返回一个32位整数。一般来说这不是一个问题,但你不能太确定;
Note: By using this, you're assuming that size
returns a 32-bit integer. Generally this isn't a problem, but you can't be too sure; use any of the above if you can.
相对于代码的另一个提示是使用 unique_ptr
/ shared_ptr
以便于内存管理:
Another tip relative to your code is to use a vector of unique_ptr
/shared_ptr
to facilitate memory-management:
std::vector<std::unique_ptr<classname>> object;
这篇关于错误C4018与向量大小()在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!