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
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;
}