c++ - 检查 std::unordered_set::find 结果的代码将无法编译

标签 c++ string compiler-errors unordered-set

我正在编写一个程序来确定字符串中的所有字符是否唯一。我正在尝试使用 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] 进行比较,但我不确定。

我该如何完成这项工作?

最佳答案

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

您可以通过将迭代器与 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容器的名称。

关于c++ - 检查 std::unordered_set::find 结果的代码将无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41374708/

相关文章:

c++ - 为什么我在尝试检查某个字段的值时得到一个奇怪的答案?

c - scanf 中的 %[^\n]s 不等待输入并被跳过

c - 使用 scanf 连续读取字符串和 int 时遇到问题

java - 我有一个不可转换的类型错误: cannot cast 'java.util.Objects' to 'byte[]' - This error is in createFromPdu()

java - 通过cmd行编译时出错

c++ - 从 boost::variant 获取 int 生成段错误

c++ - C++20 范围是否具有过滤器或 any_of 的值(非谓词)版本?

javascript - 使用 AngularJS 中的多个输入字段编辑分隔字符串

c++ - 构建提及另一种类型的对象时出错

c++ - 在eclipse中调试大输入