我需要将一个给定值与检索到的值进行比较.我在代码中多次这样做.我不满意它的外观,我正在寻找某种类型的util函数.有谁写过一个?
我在比较的值的数量在编译时是已知的.
更新:我想摆脱容器,因为我知道确切的数值(通常不超过3)我想与之比较.并且每次将物品放入容器都不太方便.如果两者
都不爱,我不爱,因为它不像"发现"那么明显.
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果你正在寻找的值是与运算符<(如int,float和std :: strings)可比,那么使用std :: set将值放在那里然后检查set.find(value)=会更快= set.end().这是因为该集合将以特定顺序存储值,以便更快地进行查找.使用哈希表会更快.但是,对于少于50个值左右你可能没有注意到任何差异:)所以我的经验法则是:
少于5项:如果有多个||
5个或更多:放入一个集合或哈希表