这个怎么样:
std::string s = "first";
if(std::set<std::string>{"first","second","third","fourth"}.count(s)>=1){
std::cout << s << " is found" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,在C++ 20及以上我认为std::set::contains更优选.
如果您希望这样做有效,那么您不会想要构造一个容器来检查该值是否存在.我们可以做的是利用C++ 17的折叠表达式并编写类似的函数
template<typename... Args, std::enable_if_t<std::conjunction_v<std::is_same<const char*, Args>...>, bool> = true>
bool string_exists(std::string to_find, Args... args)
{
return ((to_find == args) || ...);
}
Run Code Online (Sandbox Code Playgroud)
然后让你写if语句
int main()
{
std::string element;
// get value of element somehow
if (string_exists(element, "1", "2", "3", "4"))
std::cout << "found";
}
Run Code Online (Sandbox Code Playgroud)
现在没有std::string创建容器和对象.如果要接受字符串对象,可以将函数更改为
template<typename... Args, std::enable_if_t<std::conjunction_v<std::is_same<const char*, Args>...> ||
std::conjunction_v<std::is_same<std::string, Args>...>, bool> = true>
bool string_exists(std::string to_find, Args... args)
{
return ((to_find == args) || ...);
}
int main()
{
std::string element;
// get value of element somehow
if (string_exists(element, some, other, string, variables))
std::cout << "found";
}
Run Code Online (Sandbox Code Playgroud)
请注意,最后一个示例不允许您将字符串文字与std::string's 混合.
| 归档时间: |
|
| 查看次数: |
357 次 |
| 最近记录: |