Search code examples
c++stringcompiler-errorsunordered-set

Code checking the result of std::unordered_set::find won't compile


I am writing a program to determine whether all characters in a string are unique or not. I am trying to do this using an unordered_set. Here is my code:

#include <iostream>
#include <unordered_set>
#include <string>

using namespace std;

bool uniqueChars(string word) {

    unordered_set<char> set;

    for (int i = 0; i < word.length(); i++) {
        auto character = set.find(word[i]);

        // if word[i] is found in set then not all chars are unique
        if (character == word[i]) {
            return false;
        }
        //else add word[i] to set
        else {
            set.insert(word[i]);
        }
    }
    return true;
}

int main() {

    string word;
    getline(cin, word);

    bool result = uniqueChars(word);
    return 0;
}

It is giving me this error:

|15|error: no match for 'operator==' (operand types are 'std::__detail::_Node_iterator' and 'char')|

I believe that means that character is not comparable to word[i], but I'm not sure.

How do I make this work?


Solution

  • Note that std::unordered_set::find returns an iterator, not the element. It can't be compared to the element directly.

    You could check whether the element was found or not by comparing the iterator with std::unordered_set::end. e.g.

    auto character = set.find(word[i]);
    
    // if word[i] is found in set then not all chars are unique
    if (character != set.end()) {
        return false;
    }
    //else add word[i] to set
    else {
        set.insert(word[i]);
    }
    

    BTW: Better not to use set as the name of variable, which is the name of another STL container.