C++条件

paw*_*l_j 0 c++ c++14 c++17

如何检查值是否在即时创建的集中.我正在寻找一些语法糖,就像我们在python中一样

if s in set(['first','second','third','fourth']):
    print "It's one of first,second,third,fourth";
Run Code Online (Sandbox Code Playgroud)

如何在C++中高效完成?

Hir*_*oki 5

这个怎么样:

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更优选.

  • @ scohe001对于一组4个元素,您必须测量开销以查看哪个更好.即使是`std :: vector`或`std :: array`也可能是这些元素的竞争者. (5认同)
  • 或者,在C++ 20中可以使用`.contains(s)`. (2认同)
  • @pawel_j`count()`不会迭代所有元素.对于普通的`std :: set`(而不是`std :: multiset`),它与`.contains()`没有区别(除了一个看起来比另一个更漂亮). (2认同)

Nat*_*ica 5

如果您希望这样做有效,那么您不会想要构造一个容器来检查该值是否存在.我们可以做的是利用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 混合.