gpt4 book ai didi

c++:通过单个函数调用替换多个索引相等性测试

转载 作者:太空宇宙 更新时间:2023-11-04 16:05:51 24 4
gpt4 key购买 nike

在 c++/c++11 中,替换形式的多重比较的正确方法是什么:

if(isIndexToFind==index1 || isIndexToFind==index2 ...)

用一些不那么凌乱的形式:

if(isIn(indexToFind,index1,index2,...))

对于不同数量的参数 index1、index2... 此代码属于数值型,因此我希望有一些与直接比较几乎一样高效的东西。

添加 index1、index2 是常量静态值可能很有趣,因此基于可变参数模板的解决方案可能会很有趣?

最佳答案

你可以这样写

#include <iostream>
#include <algorithm>
#include <initializer_list>

template <class T>
bool one_of( const T &value, std::initializer_list<T> lst )
{
return std::any_of( lst.begin(), lst.end(), [&]( const T &x ) { return value == x; } );
}

int main()
{
std::cout << one_of( 1, { 2, 3, 1, 5 } ) << std::endl;
std::cout << one_of( 4, { 2, 3, 1, 5 } ) << std::endl;
}

关于c++:通过单个函数调用替换多个索引相等性测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35701831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com