Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading