code511788465541441 code511788465541441 - 3 months ago 12
C++ Question

What is wrong with my For loops? i get warnings: comparison between signed and unsigned integer expressions [-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;
}

Answer

Why is there a warning with -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.

How could I do better ?

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)

This saves recomputing size() at each iteration.

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)

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