burningyeti
burningyeti

Reputation: 43

How to find a certain value in a vector of strings

I'm trying to create a program for an assignment that will add and remove strings from a vector of strings, but first I need to create a function that will find whether or not the string already exists in the vector.

I've already tried to use a loop to search through the vector to find a specific desired string at each index. I tried adding a break; to exit if the string was found. I don't know if the function is supposed to be void or boolean.

bool FindString(int vctrSize, vector<string> restaurantVctr, string targetRestnt) {
    int i;

    for (i = 0; i < vctrSize; ++i) {
        if (restaurantVctr.at(i) == targetRestnt) {
            return true;
            break;
        }
        else {
            return false;
        }
    }
}

I expect the output to be true if the string was found, else it would obviously be false.

Edit: I forgot to mention that I also received the warning: "not all control paths return a value"

Upvotes: 0

Views: 3152

Answers (2)

Jeffrey
Jeffrey

Reputation: 11400

You should use std algorithms whenever possible:

auto result = std::find(restaurantVctr.begin(), restaurantVctr.end(), targetRestnt);
return result != restaurantVctr.end();

That is exactly what std::find is for.

Upvotes: 9

user10957435
user10957435

Reputation:

While I recommend using std::find as others have recommended, if you're curious what is wrong with your code, the problem is your else:

for (i = 0; i < vctrSize; ++i) {
    if (restaurantVctr.at(i) == targetRestnt) {
        return true;
        break;
    }
    else {
        return false;
    }
}

If the first item in your vector is not equal to targetRestnt, then your function returns--that is, it ends execution.

You only want to return false if it's not in the whole list--that is, you want the whole loop to execute:

for (i = 0; i < vctrSize; ++i) {
    if (restaurantVctr.at(i) == targetRestnt) {
        return true;
        // Also, you don't need a break here: you can remove it completely
        // For now, I just commented it out
        // break;
    }
}

// We didn't find it:
return false;

Upvotes: 2

Related Questions