40 template <
class InputIterator,
class T>
41 InputIterator
rfind(InputIterator rbegin, InputIterator rend,
const T &val)
43 const auto rfirst{rbegin};
44 while (rbegin != rend)
51 std::iter_swap(rbegin, rbegin - 1);
71 int main(
int argc,
char const *argv[])
79 const std::string full_path_exec{argv[0]};
80 std::string::size_type found = full_path_exec.find_last_of(
"/\\", std::string::npos);
81 const std::string exec_path = full_path_exec.substr(0, found);
82 const std::string exec_filename = full_path_exec.substr(found + 1, std::string::npos);
83 const std::string data_file_name(
"\\ch8_5.result");
86 std::string data_file_full_path{exec_path + data_file_name};
87 std::ofstream fout(data_file_full_path.c_str(), std::ios_base::app);
90 std::cerr <<
"无写权限,测试数据文件生成失败!\n";
97 timeinfo = localtime(&rawtime);
99 std::cout <<
"\nCurrent local time and date: " << asctime(timeinfo) <<
'\n';
100 fout <<
"\nCurrent local time and date: " << asctime(timeinfo) <<
'\n';
105 std::vector<size_t> vec;
111 size_t low{10}, high{25}, num_of_points{16};
113 for (
size_t i = 0; i < num_of_points; ++i)
115 iSecret = low + (high - low + 1) * rand() / (RAND_MAX + 1);
116 vec.push_back(iSecret);
120 std::vector<size_t>::iterator it;
121 std::sort(vec.begin(), vec.end());
122 it = std::unique(vec.begin(), vec.end());
123 vec.resize(std::distance(vec.begin(), it));
126 std::cout <<
"vec has " << (vec.size()) <<
" elements:\n";
127 fout <<
"vec has " << (vec.size()) <<
" elements:\n";
128 for (
auto it = vec.begin(); it != vec.end(); ++it)
130 std::cout << *it <<
", ";
137 auto target = vec.at(0);
138 for (
size_t i = 0; i < vec.size(); ++i)
140 auto result = *
Find::rfind(vec.rbegin(), vec.rend(), target);
141 std::cout <<
"*rfind(" << target <<
") = " << result <<
'\n';
142 fout <<
"*rfind(" << target <<
") = " << result <<
'\n';
146 std::cout <<
"vec has " << (vec.size()) <<
" elements:\n";
147 fout <<
"vec has " << (vec.size()) <<
" elements:\n";
148 for (
auto it = vec.begin(); it != vec.end(); ++it)
150 std::cout << *it <<
", ";
156 catch (
const std::string &e)
158 std::cerr << e <<
'\n';
161 catch (
const std::exception &e)
163 std::cerr << e.what() <<
'\n';
164 fout << e.what() <<
'\n';
170 std::cout <<
"\nIt took me " << t <<
" clicks (" << ((float)t) / CLOCKS_PER_SEC <<
" seconds).\n";
171 fout <<
"\nIt took me " << t <<
" clicks (" << ((float)t) / CLOCKS_PER_SEC <<
" seconds).\n";