【C++ Primer 习题集】(第5版)练习16.4:编写行为类似标准库find算法的模板。函数需要两个模板类型参数,一个表示函数的迭代器参数,另一个表示值的类型。使用你的函数在一个vector

时间:2024-10-27 11:30:38
#include<cstdio> #include<algorithm> #include<random> #include<vector> #include<list> #include<string> #include<chrono> #include<iostream> #pragma warning(disable:4996) using std::vector; using std::list; using std::string; using std::cout; using std::endl; using std::uniform_int_distribution; template<typename I, typename T> inline I Find(I b, const I &e, const T &v){ for (; b != e; ++b)if (*b == v)return b; return b; } void main(){ std::ios::sync_with_stdio(false); std::cin.tie(0);//关闭与stdio的同步,提高cin和cout的速率。 vector<string> u; vector<int> v; list<string> L; size_t s, s0, l, p; int a; string S; std::default_random_engine d;//随机数生成引擎,用于获得随机数。 uniform_int_distribution<int> U(-1000, 1000); uniform_int_distribution<size_t> V(1, 250), W(1, 25), D(1, 64); uniform_int_distribution<short> C(32, 126);//均匀整数分布 d.seed(std::chrono::steady_clock::now().time_since_epoch().count());//用当前系统时间作为随机引擎的种子,以在每次启动时都获取到不同的随机序列。 vector<int>::const_iterator I; list<string>::const_iterator J;//常量迭代器 for (;;){ s = V(d);//随机给出需要构造用于演示的元素的个数 for (size_t i = 0; i < s; ++i)v.emplace_back(U(d));//生成s个随机整数,整数来自均匀整数分布U puts("All values in std::vector<int> v are:"); for (I = v.cbegin(); I != v.cend(); ++I)cout << *I << ' '; cout << "\nThe size of v is " << v.size() << endl; s = W(d); cout << "\nDemonstrating " << s << " times of calling the function Find():\n"; for (size_t i = 0; i < s; ++i){ a = U(d); cout << "Finding " << a << ":\n"; I = Find(v.cbegin(), v.cend(), a); if (I == v.cend())cout << "WARNING: " << a << " not found.\n"; else cout << " " << a << " is at position " << I - v.cbegin() << '\n'; } cout << endl; s = V(d) >> 1 | 1; s0 = s - 1;//s的大小是随机数V(d)的一半,且通过与1按位或来确保不为零,防止后续执行出错 for (size_t i = 0; i < s; ++i){//生成s个随机字符串,每个字符串的长度随机 S.clear(); l = D(d); for (size_t j = 0; j < l; ++j)S += C(d); L.emplace_back(S); u.emplace_back(S); } puts("All strings in std::list<std::string> L are:"); for (J = L.cbegin(); J != L.cend(); ++J)cout << *J << '\n'; cout << "The size of L is " << L.size() << endl; s = W(d); cout << "\nDemonstrating " << s << " times of calling the function Find():\n"; uniform_int_distribution<size_t> X(0, s0); for (size_t i = 1; i < s; ++i){ p = X(d); cout << "Finding " << u[p] << '\n';//p为链表中的从开头数起的第p个字串 J = Find(L.cbegin(), L.cend(), u[p]); if (J == L.cend())cout << "WARNING: " << '\"' << u[p] << '\"' << " not found.\n"; else cout << " Found " << *J << '\n'; } J = Find(L.cbegin(), L.cend(), "fhdsighishgkshdklguwehjaoiorjsdui");//演示一个一定找不到的例子 if (J == L.cend())cout << "WARNING: " << "\"fhdsighishgkshdklguwehjaoiorjsdui\"" << " not found.\n"; else cout << " Found " << *J << '\n'; cout << endl; u.clear(); v.clear(); L.clear(); system("pause"); } }