简体   繁体   中英

C++ Error - warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

I'm trying to implement a sorting program of numbers, but am getting the following error:

错误

I was able to compile and work the code on an online c++ compiler, but when I must run it via the terminal so after attempting to do so, it won't compile anymore. There's actually nothing wrong with the code itself, since they're just warnings. But I would like to know how to fix them all, please!

The errors come from these parts of my code:

void sort()
{

    int i, j;

    for (i = 0; i < storage.size()-1; i++)
    {

        for (j = 0; j < storage.size()-i-1; j++)
        {
            if (storage[j] > storage[j+1]) // swap the values
            {
                int temp = storage[j];
                storage[j] = storage[j+1];
                storage[j+1] = temp;
            }
        }
    }
}

void print()
{
    
    for(int i = 0; i < storage.size(); i++)
        cout<<storage[i]<<" ";
        cout<<endl;
    }
    
    vector<int> getList()
    {
        return storage;
    }
    
    void setList(vector<int> list)
    {
        storage = list;
    }
};

   void quickSort(int start, int end)

   {

   if (start < end)
   {
       int part = partition(start, end);
       quickSort(start, part - 1);
       quickSort(start + 1, end);
   }
   }

   void sort()
   {
       quickSort(0, storage.size() - 1);
   }

   void print()
   {
for(int i = 0; i < storage.size(); i++)
cout<<storage[i]<<" ";
cout<<endl;
   }

Any help will be much appreciated. Thank you!

would like to know how to fix them all, please!

The diagnostic says that you are comparing numbers of different signedness. You can fix that by not comparing numbers of different signedness. You can go with using signed type on both sides or unsigned type on both sides.

Aside from the warning, storage.size()-1 is a dangerous operation unless you first enforce that the container is non-empty. If you subtract from a unsigned zero, you get a very large unsigned value. That is not bad by itself, but when you eventually use that large value as subscript, you get undefined behaviour. Simple solution to this is to add +1 to both sides of the comparison: i+1 < storage.size() .

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