将一个字符与一组字符进行比较的C++代码

7
有没有一种方法可以将单个字符与一组字符进行比较?
例如:
char a;
if(a in {'q','w','e','r','t','y','u'})
      return true;
else return false;

我需要类似于这样的东西。
4个回答

18
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>),但除非你每秒要执行几百万次,否则这太过复杂。


@Erik:我建议你至少抄袭一些我的使用集合的代码。count很好用 :-) - Steve Jessop
@Erik:说得好。我认为setmapcount函数实际上是隐藏的contains函数,所以可读性只是熟悉度的问题。当然,对于multi_setmulti_map来说,这可能会导致效率低下。 - Steve Jessop
@Steve: 你怎么知道 set 不是低效的呢?你确定因为它只能是0或1,就会在第一次出现时停止吗? - stefaanv
@stefaanv:从理论上讲,这并不重要。即使它检查了下一个元素,它仍然是O(log N)+O(1),仍然是O(log N)。实际上,库的实现者非常有能力。 - MSalters
@Steve 和 @MSalters:谢谢,我只是在问这个问题因为这经常阻止我使用 count(),因为 find() 是保证 O(log N) 的。 - stefaanv
显示剩余2条评论

11

使用strchr函数:

return strchr("qwertyu", a);

没有必要写成 "if x return true else return false",只需写成 "return x" 即可。


需要注意的是,strchr 函数在 <cstring>/<string.h> 头文件中。 - Rune Aamodt

0
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 {
    ...
}

0
std::string s="qwertyu";
return s.find(a) != std::string::npos;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接