我有一个字符串,如果字符串值与给定的一组单词匹配,我想执行if语句(比如猿、吃、睡、芒果.)
我能做到:-
if(name=="ape" || name=="eat".............)有什么更简单的方法吗?
我只想用其他的。
发布于 2019-10-08 13:17:42
Decalare是一个单词数组,然后使用标准算法std::find或std::any_of。
例如
const char * words[] =
{
"ape", "eat", "sleep", "mango"
};
if ( std::find( std::begin( words ), std::end( words ), name ) != std::end( words ) )
{
//...
}如果要声明排序数组,则可以使用标准算法std::binary_search。
这里有一个演示程序
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
const char * words[] =
{
"eat", "ape", "mango", "sleep"
};
std::string name( "mango" );
if ( std::binary_search( std::begin( words ), std::end( words ), name ) )
{
std::cout << name << " is a correct name\n";
}
return 0;
}其输出是
mango is a correct name或者将单词放在标准容器中,例如std::set,并使用容器的查找方法。
发布于 2019-10-08 13:18:41
如果您希望只使用if和else,而不添加任何内容,则不存在这种情况。
否则,您可以使用std::unordered_set,用这些单词填充它,并使用find()。
发布于 2019-10-08 13:20:21
for(auto pattern: {"ape", "eat"}) {
if(name == pattern) {
// all the consequences here
break;
}
}或者,在热路径上,您可以使用类似哈希集的内容:
static const std::unordered_set<std::string> words{"ape", "eat"};
if(words.find(name) != words.end()) {
}只需确保它是一个static const,不要每次重新初始化它。如果您有大量的模式可供使用,可能会更好。
https://stackoverflow.com/questions/58287145
复制相似问题