我需要将一个给定值与检索到的值进行比较。我在代码中多次这样做。我对它的外观不满意,我正在寻找某种 util 函数。有人写过一篇吗?
我要比较的值的数量在编译时是已知的。
Update:我想摆脱容器,因为我知道我想要比较的确切值数量(通常不超过 3)。而且每次都将物品放入容器中也不是那么方便。
我不爱if两者都不是因为它不像“查找”那么明显。
#include <algorithm>
#include <string>
#include <vector>
std::string getValue1()
{
return "test";
}
std::string getValue2()
{
return "the";
}
std::string getValue3()
{
return "world";
}
int main()
{
const std::string value = "the";
// simple if
if ( value == getValue1() ||
value == getValue2() ||
value == getValue3() )
return 1;
// using collections like vector, set
std::vector<std::string> values;
values.push_back( getValue1() );
values.push_back( getValue2() );
values.push_back( getValue3() );
if ( values.end() != std::find( values.begin(), values.end(), value ) )
return 1;
// third option I'd use instead
//
return 0;
}
如果您要查找的值与operator
少于 5 项:如果有多个 ||
5个或更多:放入集合或哈希表中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)