有没有一种方法可以将单个字符与一组字符进行比较?
例如:
我需要类似于这样的东西。
例如:
char a;
if(a in {'q','w','e','r','t','y','u'})
return true;
else return false;
我需要类似于这样的东西。
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>
),但除非你每秒要执行几百万次,否则这太过复杂。
使用strchr函数:
return strchr("qwertyu", a);
没有必要写成 "if x return true else return false",只需写成 "return x" 即可。
const char[] letters = {...};
char a = ...;
bool found = false;
for(int i = 0; i < sizeof(letters); i++) {
if (letters[i] == a)
found = true;
}
if (found) {
...
} else {
...
}
std::string s="qwertyu";
return s.find(a) != std::string::npos;
count
很好用 :-) - Steve Jessopset
和map
的count
函数实际上是隐藏的contains
函数,所以可读性只是熟悉度的问题。当然,对于multi_set
和multi_map
来说,这可能会导致效率低下。 - Steve Jessop