有没有一种方法可以将一个
char
与char
列表中的每个元素进行比较?char ch;
if(ch == 'a' || ch == 'b' || ch == 'c')
是否有方法只进行以下操作
if(ch is one of {a, b, c})
char
与char
列表中的每个元素进行比较?char ch;
if(ch == 'a' || ch == 'b' || ch == 'c')
是否有方法只进行以下操作
if(ch is one of {a, b, c})
当你可以直接这样做时,为什么要编写lambda表达式或使用临时字符串对象:
if (strchr("abc", ch))
"abc"
首先被绑定到一个字符串上,std::string s = "abc"
。在这里使用strchr
是否不正确? - Marsstrchr(some_string.c_str(), ch)
可以工作,但除非你有一个字符串对象出于其他原因,否则这将是浪费。构造 std::string
对象相对昂贵。 - Ben Voigt使用:std::any_of
在 C++11 中:
std::string str="abc";
if(std::any_of(str.cbegin(), str.cend(),
[ch](const char& x){return x==ch; } ))
{
}
struct comp
{
comp(char x) :ch(x){}
bool operator()(const char& x) const
{
return x == ch;
}
char ch;
};
if(std::any_of(str.cbegin(), str.cend(),comp(ch) ))
{
}
编辑:为了使用C++的<algorithm>
,可以尝试使用std::any_of
,但可能不够高效。
std::find
的解决方案,因为它更清晰地传达了你想要做什么。 - Escualostrchr
,再次之后是字符数组中的std::find
或std::any_of
,最慢的则是在可抛弃的字符串对象中进行迭代。 - Ben VoigtC++
就开始对 STL 的 "算法方式" 着迷。 - P0Wstd::find
。假设chars
是您的字符数组,您需要查找ch
。if(std::find(std::begin(chars), std::end(chars), ch) != std::end(chars))
string abc("abc");
if (abc.find(ch) != string::npos) {
...
}
find
比 <algorithm>
中的通用版本更易于使用(和阅读)。它甚至可以与临时的 string
对象一起使用,例如 string("abc").find(ch)
或者使用用户定义字面量 "abc"str.find(ch)
。但与 <string.h>
的方式相比仍然非常冗长。 - Ben Voigtstd::string
主要是出于"意识形态原因",虽然 C 库的函数在 C++ 中也完全可以使用。 - Sergey Kalinichenko if(ch >= 'a' && ch <= 'c')
我还为此情况使用了 fall-through switch:
switch(ch)
{
case 'a':
case 'b':
case 'c':
case 'e':
...
break;
}
有些人不喜欢使用穿透switch/case语句,但我认为它比一个庞大的布尔逻辑更少出错,并且在使用数据结构时性能更好。编译器处理switch语句非常出色。
if(ch >= 'a' && ch <= 'm')
的代码将失败。 - Crowman('z' - 'a' == 25)
比C++本身更具可移植性是一个安全的赌注。 - Benjamin Lindleytemplate <typename Key, typename Value>
inline bool in(const Key& key, const Value& value) {
return key == value;
}
template <typename Key, typename Value0, typename ...ValueN>
inline bool in(const Key& key, const Value0& value, ValueN &&...args) {
return (key == value ? true : in(key, std::forward<ValueN>(args)...));
}
。
if (in(some_string, "base", "os", "io", "coroutine", "debug")) ...
但是支持比较的其他类型(如char
)也应该可以正常工作。
希望能够帮到你。祝好运!
作为另一种选择,可以创建一个包含字符的set
,并检查它是否在其中;
std::set<char> mySet = {'a','b','c'}; // C++11 initializer list
if(mySet.find('d') != mySet.end()) {
...
}
我有点惊讶,竟然没有人建议使用find_first_of。
char c('e');
// we can check if c is undesirable
const std::string unwanted("abc");
bool undesirable = (unwanted.find_first_of(c) != std::string::npos);
// OR we can check if c is desirable
const std::string wanted("def");
bool desirable = (wanted.find_first_of(c) != std::string::npos); //..or check if it's desirable.
我使用这个(也许我不应该?)来忽略字符串迭代器中不需要的字符...
/** in and out are string iterators.
* skip over any undesirable characters by matching
* against desirable and looking for npos.
**/
const std::string ok("!+-./0123456789:^ABFIORmn");
while (ok.find_first_of(*in) == string::npos && in < out) {
in++;
}
std::find
或尝试维护一个字符串而不是字符列表。 - andrestrchr()
函数。 - Crowmanstrchr
确实比答案中使用的任何“现代 C++”方法都要简单得多。 - Ben Voigt