在 644 - Immediate Decodability 的解法中, 为了查找一个字符串是否在一个 vector 中, 使用了 <algorighm> 中的 search 函数, 感受很不优美; 后来发出 find_if 函数能够知足我最初的想法, 使用 find_if 实现的代码以下: ios
有几个新知识点:
1. find_if 能够指定一个自定义 unary 函数进行比较.
2. 使用 bind1st 把 binary 函数转为 unary 函数.
3. 使用 ptr_fun 把 function pointer 转化为 function object.
c++
代码:
函数
# include <iostream> # include <string> # include <cstdio> # include <cstring> # include <vector> # include <algorithm> # include <functional> // bind1st # include <cctype> using namespace std; // bind1st 或 bind2nd 在这里都是可用的,c++ 11 中 bind 更好用 // ptr_fun 转 function 指针为函数对象 // 如果简单的相等,能够直接用 equal_to<string>() // 比较两个字符串相等, 当一个字符串是另外一个字符串的前缀时也相等 bool immediateCompare(string str1, string str2){ int len = min(str1.size(), str2.size()); for(int i=0; i<len; i++){ if(str1[i] != str2[i]) return false; } return true; } int main(int argc, char const *argv[]) { #ifndef ONLINE_JUDGE freopen ("644_i.txt", "r", stdin); freopen ("644_o.txt", "w", stdout); #endif int groupNum = 0; string line; bool immediately = true; vector<string> group; while(!cin.eof()){ getline(cin, line); // 新的一个 group 开始, 输出并重置 immediately 和 group if(line == "9"){ if(immediately){ cout << "Set " << ++groupNum << " is immediately decodable" << endl; }else{ cout << "Set " << ++groupNum << " is not immediately decodable" << endl; } immediately = true; group.clear(); continue; } // 若是前面已经判断出是 not immediately 了, 那么后面的操做无需再进行 if(!immediately) continue; // 判断 group 中是否有和当前 line 为前缀的字符串, 如有, 则 immediately 为 true if(find_if(group.begin(), group.end(), bind1st(ptr_fun(immediateCompare), line)) != group.end()) immediately = false; group.push_back(line); } return 0; }
环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE
spa