1、原代码:
if( strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()||
strkey.comparenocase()
)
{
}
优化后的代码:
char ** array={"a", "b"};
int len = ARRAYSIZE(array);
const char ** where = std::find_if(array, array+len, std::bindlst(std::equal_to<std::string>(), strKey));
if(where != (array+len))
{
std::cout<<"find it";
}
2、原代码:
(关于 将某字符串要映射给其他类型)
std::map<std::string, int> mapTest;
mapTest.insert("aoo", 1);
...
int nIndex = mapTest["aoo"];
转化后的代码:
struct kv
{
std::string strKey;
int nValue;
}
struct finder
{
kv key;
finder(std::string strTmp)
{
key.strKey = strTmp;
}
bool operator()(const kv & tmp)
{
return tmp.strKey==key.strKey;
}
}
kv ** kvArray = {{"1", 1}, {"2",2}};
int len = sizeof(kvArray)/sizeof(kv);
finder find("1");
kv * pFound = std::find_if(kvArray, kvArray+len, find);
PS:关于第二种优化,我不知道这算不算是一种优化手段,当kvArray特别多值时,这可能只是减少代码行数,这里就先做记录~