在一组字符串中找到一个字符串,我当然可以使用std :: find,std :: upper_bound或std :: lower_bound,但是我必须传递所有这些开始和结束迭代器。
现在-我有一组要匹配的字符串和一个变量。这组字符串在编译时是已知的,我非常想删除当前调用的冗长性,例如
if (std::find({"first", "string", "here"}, searchedStr) != std::notfound)
现在,我知道std :: notfound不存在,这只是为了说明。
我在C ++上有这样的东西吗?查看文档,我找不到任何东西。由于红黑树的实现,我也不能使用std :: set,这会使我的工作变慢。
最佳答案
您不需要initializer_list
。请改用可变参数模板:
template <typename T, typename... Ts>
bool matches_any(const T& needle, const Ts&... haystack)
{
// You might want to be smarter here and use `strcmp` if
// comparing C-style strings.
return ((needle == haystack) || ...);
}
我在上面使用的是C ++ 17折叠表达式,但是C ++ 11和C ++ 14还有其他选择(请查找
for_each_argument
)。用法:
if(matches_any(searchedStr, "first", "string", "here")) { /* ... */ }
live wandbox example