C++ comparing bunch of values with a given one

后端 未结 10 922
一向
一向 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 07:00

    How about using a boost::array (or std::tr1::array) and creating a simple function like this:

    template 
    bool contains(const boost::array& arr, const ValueType& val)
    {
        return std::find(arr.begin(), arr.end(), val)!=arr.end();
    }
    

    You could then reuse that pretty easily:

    #include 
    #include 
    
    #include 
    
    template 
    bool contains(const boost::array& arr, const ValueType& val)
    {
        return std::find(arr.begin(), arr.end(), val)!=arr.end();
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        boost::array arr = {"HI", "there", "world"};
    
        std::cout << std::boolalpha 
            << "arr contains HI: " << contains(arr, std::string("HI")) << std::endl
            << "arr contains blag: " << contains(arr, std::string("blag") ) << std::endl
            << "arr contains there: " << contains(arr, std::string("there") ) << std::endl;
    
        return 0;
    }
    

    Edit: So boost is out. It's pretty easy to adapt this to a regular array:

    template 
    bool contains(ValueType (&arr)[arraySize], const ValueType& val)
    {
        return std::find(&arr[0], &arr[arraySize], val)!=&arr[arraySize];
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        std::string arr[3] = {"HI", "there", "world"};
    
        std::cout << std::boolalpha << "arr contains HI: " << contains(arr, std::string("HI")) << std::endl
            << "arr contains blag: " << contains(arr, std::string("blag") ) << std::endl
            << "arr contains there: " << contains(arr, std::string("there") ) << std::endl;
    
        return 0;
    }
    

提交回复
热议问题