我正在编写一个程序来确定字符串中的所有字符是否唯一。我正在尝试使用 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/