2
votes

I'm doing an exercise to reverse the order of a vector. My program works, but I am getting a warning in the for loop I am executing below:

    void reverse (vector<int>& v){
        for(int i=0; i<v.size()/2; ++i){
            swap(v[i],v[v.size()-1-i]);
        }
    }

on the line of the for loop, I am getting the warning message "comparison between signed and unsigned integer expressions [-Wsign-compare]". I am using Stroustrop's Programming Principles and Practice Using C++, and he uses basically that general format (without the / 2). Should I be writing this for-loop differently?

2
The result of v.size() is unsigned (size_t is unsigned). Therefore i<v.size()/2 is a signed vs. unsigned comparison. Since your i will never be negative, you could define i as unsigned int or uint32_t or size_t.phonetagger
Since i will never be negative, there is no real issue here. Your compiler is warning you that you might not be smart enough to understand the code that you've written, and should consider changing it to something that the compiler writer approves of.Pete Becker

2 Answers

1
votes

The size function in a vector returns a size_t which is basically an unsigned int. When you get a warning like that, check the variable types that you are being warned about. One way of getting rid of the warning is to change the loop variable

for(size_t i=0; i<v.size()/2; ++i)

The problem is that still computes v.size()/2 every time. So a better way would be

for(size_t i=0, stop=v.size()/2; i < stop; ++i)
0
votes

The size() function in the std::vector class returns a size_t value, which is always defined as an unsigned type (though its bit-width may vary between platforms). This is generally true of all standard functions that return container, array or string size values (like std::strlen()), and the type is also used as the actual type for array indexes, and parameters to operators such as new int[n].

To avoid the warning, simply declare your loop variable (i) as a size_t rather than a (signed) int:

    void reverse (vector<int>& v){
        for(size_t i=0; i<v.size()/2; ++i){
            swap(v[i],v[v.size()-1-i]);
        }
    }