有符号和无符号整数表达式之间的比较
comparison between signed and unsigned integer expressions?
目前正在编译我的set.cpp文件(我们必须根据set.h文件和test_set.cpp制作该文件(使用g ++编译器,我不断遇到以下警告:
set.cpp: In member function âvoid set::remove(const set::value_type&)â:
set.cpp:30: warning: comparison between signed and unsigned integer expressions
set.cpp: In member function âbool set::contains(const set::value_type&) constâ:
set.cpp:50: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âset set_union(const set&, const set&)â:
set.cpp:65: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âset set_intersection(const set&, const set&)â:
set.cpp:76: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âset set_difference(const set&, const set&)â:
set.cpp:90: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âbool is_subset(const set&, const set&)â:
set.cpp:104: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âbool operator==(const set&, const set&)â:
set.cpp:118: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âstd::ostream& operator<<(std::ostream&, const set&)â:
set.cpp:131: warning: comparison between signed and unsigned integer expressions
我不确定这些是什么意思,并且想知道如何解决这个问题。
您收到的警告很可能来自 for 循环:
例:
void set::remove(const value_type& entry)
{
for(int i = 0; i < used; i++) //the comparison in question is on this line
{
if(data[i] == entry)
{
data [i] = data [used - 1];
used --;
return;
}
}
}
语句:i < used
正在比较i
,这是一个int
,used
我假设它是无符号的类型。
如果您查看警告中指定的每个行号,我相信它们都对应于函数中的 for 循环。
修复这些警告的最简单方法是将int
替换为您用于used
的任何类型。
例如,如果used
是并且unsigned int
则您的 for 循环将变为:
void set::remove(const value_type& entry)
{
for(unsigned int i = 0; i < used; i++)
{
/*...*/
}
}
在没有看到您的头文件的情况下,我假设used
被定义为unsigned int
。在循环中,您将i
定义为int
,从而导致警告。
负值计算结果为无符号整数中的大正数,因此比较两者可能会导致意外结果。快速的解决方案是将i
的所有用法更改为unsigned int
或用于used
的任何实际类型。
相关文章:
- 禁止指针和整数之间的比较C++
- ISO C++禁止指针和整数 [-fpermissive] [c++] 之间的比较
- 比较它们之间的元素并获取公共值的键
- 零点和布尔值之间的比较
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- C++ - 负数和正数之间的比较返回 false
- Qt 错误 iso c++ 禁止指针和整数之间的比较 -permissive
- C++模板参数之间的比较似乎被忽略了
- 为什么C++容器之间存在比较运算符
- 错误:ISO C++禁止在指针和整数 [-fallowive] 之间进行比较
- 数字之间的比较
- C++ - 比较模板和类之间的数据类型
- 获取字符串大小的各种方法之间的比较
- 比较器的两个实现之间的差异
- 如何修复C++中的"指针和整数之间的比较"错误?
- 不同指针类型之间的无效比较:'type*' 和 'type&(*)()'
- 符号和未签名整数表达式之间的比较,以进行循环误差
- 比较C 中移动和智能指针之间的习惯
- 消除有符号和无符号整数表达式之间比较的优雅方式
- 无法理解浮点数和对象实例化之间比较的原因