C++ comparing bunch of values with a given one

后端 未结 10 920
一向
一向 2021-01-21 06:02

I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util

10条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 06:49

    It depends on the source of the retrieved values, if you're reading in from a file or stream then you'd do something different but if your source is a series of functions then the following is a different way to do it, not perfect but may suit your needs:

    const int count = 3;
    std::string value = "world";
    boost::function funcArray[count];
    funcArray[0] = &getValue1;
    funcArray[1] = &getValue2;
    funcArray[2] = &getValue3;
    
    for( int i = 0; i < count; ++i )
    {
        if( funcArray[i]() == value )
            return 1;
    }
    

    If you know which functions are the source (as well as the count of objects) I expect you could assemble the function pointer array using the preprocessor.

提交回复
热议问题