简体   繁体   中英

warning: comparison between signed and unsigned integer expressions..how to solve it?

i am getting a comparison between signed and unsigned integer expression in my code:

    vector<long int> row;
    long n,m;
    long int pro=1;
    cin>>n;
    for(long i=0;i<n;i++)
    {
        long int temp;
        for(long j=0;j<n;j++)
        {
            cin >> temp;
            row.push_back(temp);
        }
    }

    cin >> m;
    for(long i=0;i<row.size();i++)
        pro = pro * pow(row[i],m);

    long int mod = 1000000007;
    cout<< (long int)pro%mod;

At the line: for(long i=0;i<row.size();i++)

How can I fix this warning?

std::vector::size returns a value of size_type , which is Unsigned integral type (usually std::size_t ) .

Your loop count variable is of type long which is a signed type. So in the loop condition you are comparing a signed and an unsigned type.

The solution is simple: Use std::vector<long int>::size_type (or maybe even size_t ) instead of long .

vector::size returns a size_type which is an unsigned integral value.

You can fix this one of two ways:

  1. Use an unsigned iterator in your for -loop: for(auto i = 0U; i < row.size(); ++i)
  2. Cast the return of vector::size to a signed integer: for(auto i = 0; i < static_cast<int>(row.size()); ++i)

C++ has a thing called the range-based for loop , which relieves you from the burden of dealing with index variables. It also solves your mismatched signedness problem:

for(long r : row)
    pro = pro * pow(r,m);

Just use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM