我的For循环有什么问题?我得到警告:有符号和无符号整数表达式之间的比较[-Wsign-compare] [英] What is wrong with my For loops? i get warnings: comparison between signed and unsigned integer expressions [-Wsign-compare]

查看:1926
本文介绍了我的For循环有什么问题?我得到警告:有符号和无符号整数表达式之间的比较[-Wsign-compare]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string>
#include <vector>
#include <sstream>


using namespace std;

int main() {

    vector<double> vector_double;
    vector<string> vector_string;
    ...


    while (cin >> sample_string)
        {
            ...
        }

    for(int i = 0; i <= vector_string.size(); i++)
        {
            ....
        }

    for (int i = 0; i < vector_double.size(); i++)
        ....


    return 0;
}


推荐答案


为什么 -Wsign-compare ?会出现警告

警告名称及其文本,暗示,问题是您正在比较有符号和无符号整数。通常假设这是一个意外。

As the name of the warning, and its text, imply, the issue is that you are comparing a signed and an unsigned integer. It is generally assumed that this is an accident.

为了避免这个警告,你只需要确保< (或任何其他比较运算符)既有签名,又有无符号。

In order to avoid this warning, you simply need to ensure that both operands of < (or any other comparison operator) are either both signed or both unsigned.


/ p>

How could I do better ?

编写用于循环的惯用方法是初始化 both 第一个语句中的计数器和限制:

The idiomatic way of writing a for loop is to initialize both the counter and the limit in the first statement:

for (std::size_t i = 0, max = vec.size(); i != max; ++i)

你也可以(也许应该)使用迭代器,而不是索引:

You could also (and probably should) use iterators instead of indices:

for (std::vector<int>::iterator it = vec.begin(), end = vec.end(); it != end; ++it)

迭代器适用于任何类型的容器,而下标限制为C -arrays, deque 向量

Iterators work for any kind of containers, while indices limit you to C-arrays, deque and vector.

这篇关于我的For循环有什么问题?我得到警告:有符号和无符号整数表达式之间的比较[-Wsign-compare]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆