gpt4 book ai didi

c++ - 将一个字符与一组字符进行比较 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:06 24 4
gpt4 key购买 nike

有没有办法比较单个字符和一组字符?

例如:

char a;
if(a in {'q','w','e','r','t','y','u'})
return true;
else return false;

我需要这样的东西。

最佳答案

std::string chars = "qwertyu";
char c = 'w';
if (chars.find(c) != std::string::npos) {
// It's there
}

或者您可以使用集合 - 如果您需要经常查找,那会更快。

std::set<char> chars;
char const * CharList = "qwertyu";
chars.insert(CharList, CharList + strlen(CharList));
if (chars.find('q') != chars.end()) {
// It's there
}

编辑:正如 Steve Jessop 所建议的:您也可以使用 chars.count('q')而不是 find('q') != end()

您也可以使用当前字符的位图(例如 vector<bool> ),但这太复杂了,除非您每秒执行几百万次。

关于c++ - 将一个字符与一组字符进行比较 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5565082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com