Untitled
unknown
c_cpp
2 years ago
1.4 kB
4
Indexable
#include <string> #include <iostream> #include <sstream> #include <vector> #include <cctype> #include <algorithm> using std::stringstream; using std::string; using std::cout; using std::endl; using std::vector; using std::tolower; using std::transform; #define PRINT(X) cout << (#X) << " = " << X << endl // transforms a string to lowercase // exists in popular libraries such as "boost" string str_tolower(string s) { // This is a "lambda". // Interface fix because standard library `tolower` has a weird type. auto my_tolower = [](unsigned char c){ return tolower(c); }; transform(s.begin(), s.end(), s.begin(), my_tolower); return s; } int search(string target, vector<string> const& lst) { target = str_tolower(target); // Lambda to check whether a string is the target auto is_target = [&](string s) { return target == str_tolower(s); }; // Standard library function that searches a vector auto it = find_if(lst.begin(), lst.end(), is_target); // If not found if(it == lst.end()) return -1; // If found, compute and return index return it - lst.begin(); } int main() { vector<string> v {"Aaa", "Bbb", "Ccc"}; PRINT(search("BBB", v)); // 1 PRINT(search("DDD", v)); // not found: -1 PRINT(search("aaa", v)); // 0 return 0; }
Editor is loading...