检查 std::unordered_set::find 结果的代码不会编译

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

我正在编写一个程序来确定字符串中的所有字符是否唯一。我正在尝试使用 unordered_set 来执行此操作。这是我的代码:

#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;
}

它给我这个错误:

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

我认为这意味着该字符无法与 word[i] 相媲美,但我不确定。

如何进行这项工作?

*character == word[i] 

( This is the way to access the characters but it is not needed and it should be guided by a check whether it points to the past to the last element)

*字符基本上是引用已插入的字符。

  if(character != set1.end() )
     return false; // as we are sure  that it is not unique character string

您必须取消引用它。但在那种情况下,你还需要做是否 return 指向 `set::end`` 的迭代器。

顺便说一下,有一种非常简单的方法可以完成您想要做的事情。

bool uniqueChars(string word) {

    unordered_set<char> set1;

    for (int i = 0; i < word.length(); i++) 
        auto character = set1.insert(word[i]);

    return set1.size()==word.length();
}

"set"是c++中的关键字

请注意,std::unordered_set::find returns 是一个迭代器,而不是元素。它不能直接与元素进行比较。

您可以通过将迭代器与 std::unordered_set::end 进行比较来检查是否找到了元素。例如

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]);
}

顺便说一句:最好不要使用 set 作为变量名,它是另一个 STL 容器的名称。

利用 insert 的 return 价值。它会告诉您在插入过程中是否发现了重复项(在这种情况下没有插入任何内容)。

bool uniqueChars(string word) {
    unordered_set<char> set;
    for ( char c : word ) {
        if ( ! set.insert( c ).second ) {
            return false; // set didn't insert c because of a duplicate.
        }
    }
    return true; // No duplicates.
}

但是,这并不像看起来那么有效。 unordered_set 是一个基于堆的哈希 table 并且它的实现相当重量级。轻量级位向量非常适合对字符进行分类。

#include <bitset>

constexpr int char_values = numeric_limits< char >::max()
                          - numeric_limits< char >::min() + 1;

bool uniqueChars(string word) {
    bitset< char_values > set;

    for ( char c : word ) {
        int value_index = c - numeric_limits< char >::min();

        if ( set[ value_index ] ) {
            return false;
        } else {
            set[ value_index ] = true;
        }
    }
    return true; // No duplicates.
}