-1

I am using a function to return a vector of integers, but the problem is that if I type return out inside the if statement it gives me an error. If I type it out of for loop the code works. After the if statement works, I need to force the loop to stop and returning the out vector.

vector<int> icecreamParlor(int m, vector<int> arr) {
    vector<int> out;
    for(int i = 0 ; i < arr.size(); i++){
        int x  = arr [i];
        for(int z = 1 ; z < arr.size(); z++){
            if(x + arr[z] == m){
                out.push_back(i+1);
                out.push_back(z+1);
                return out;
            }
        }
    }
} 

THis is the error massage

Solution.cpp: In function ‘std::vector<int> icecreamParlor(int, std::vector<int>)’:
Solution.cpp:10:23: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<int>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]
     for(int i = 0 ; i < arr.size(); i ++){
fabian
  • 80,457
  • 12
  • 86
  • 114
  • 2
    If the condition `x + arr[z] == m` is never true, what do you return then? – Some programmer dude Feb 07 '21 at 12:51
  • 1
    Not all code paths return a value. You probably want to return after the first loop completes and not within the loops? – Raildex Feb 07 '21 at 12:51
  • 1
    And what errors do you actually get? Please [edit] your question to include a *full* and *complete* copy-paste of the errors. And preferably a [mcve] to go with the errors. – Some programmer dude Feb 07 '21 at 12:52
  • Typically, the error itself tells you why it was given. It's called an "error message". – eerorika Feb 07 '21 at 12:58
  • Quick fix for the *warning* you show (which shouldn't be the only one): `for (size_t i = 0; ...` Same for the second loop with `z`. – Some programmer dude Feb 07 '21 at 13:02
  • Simplest case where you should see the issue: pass in an empty vector and the loop body of the outer loop is never entered so the function doesn't pass a `return` statement. The compiler doesn't like this. Depending on the desired result an additional `return out;` at the end of the function may result in the desired outcome. – fabian Feb 07 '21 at 13:02

1 Answers1

0

The quoted "error" (which is, in fact, a warning) is about

 i < arr.size()

Unfortunately. the size() function of the vector, for historical reasons, returns an unsigned type. When comparing a signed and unsigned integers, the signed integer gets converted to an unsigned integer with potentially catastrophic outcome (if it was in fact negative). Hence the warning. You can

  • use the new ssize() member function which is the same as size but returns a signed integer.
  • declare i to be unsigned as well (be careful though when doing this with reverse iteration)
  • cast size() to a signed integer: i < (int)v.size()

I suspect your compiler must also warn you that not all control paths of your function return a value.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434