find() not working for a character in a string (C++)

Advertisements

So i am using find in the algorithm library of C++ to check if each character in a string is present in a string vector, but the problem i am facing with the find function is that this does not work:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
    
    string s = "hello";
    vector<string> v = {"h", "e", "l", "o"};
    if(find(v.begin(), v.end(), s[0]) != v.end()) {
        cout << "found";
    }
    return 0;
}

But replacing s[0] with a string literal like this works:

if(find(v.begin(), v.end(), "h") != v.end()) {
        cout << "found";
    }

Checking online I found that [] operator returns a reference to a char, so i tried de-referencing it as *s[0] which gave the error:

invalid type argument of unary ‘*’

>Solution :

s[0] is a character, so it cannot directly compared to strings.

You can make it work by first constructing a string from a character.

if(find(v.begin(), v.end(), string(1, s[0])) != v.end()) {
    cout << "found";
}

Another option is using a substring as the query.

if(find(v.begin(), v.end(), s.substr(0, 1)) != v.end()) {
    cout << "found";
}

Leave a ReplyCancel reply