Home > Software engineering >  How to check if a number is in a vector, and if not, then to return -1?
How to check if a number is in a vector, and if not, then to return -1?

Time:09-02

This is pretty easy if I can import <algorithm> or any other things at the top, but I just started using C and my professor asked us to use only loops and conditionals for this problem.

The problem itself is to give a vector v and an int seek to a function. A loop runs through the vector to find the index of the first location of the number. If it can be found, then return the index of where the number is, if not then return -1.

I got the first part down, but now I am having an issue with the second part.

#include <iostream>
#include "vectorutils.h"
#include <vector>


using namespace std;
//endl = new line


int main() {
    cout << find({1, 2, 3, 4, 5, 6, 7, 8}, 28) << endl;
}

int find(const std::vector<int>& v, int seek) {
    int ind = 1;
    for (int i = 0; i < v.size(); i  ) {
        if (seek == v[i]) {
            return i;
        }
    else {
            return -1;
    }
}

CodePudding user response:

You have the return -1; statement in the wrong place. It needs to be after the loop exits, not inside the loop. For example:

int find(const std::vector<int>& v, int seek) {
    for (int i = 0; i < v.size(); i  ) {
        if (seek == v[i]) {
            return i;
        }
        // else {
        //    return -1;
        // }
    }
    return -1; // <-- moved down here!
}

In your original code (if it could compile, which it doesn't), the logic is wrong. If the vector is empty then you return nothing at all (which is undefined behavior), and if the 1st element does not match the number then you return -1 immediately without checking the remaining elements at all.

The above change fixes both of those issues.

  •  Tags:  
  • c
  • Related