实验1 现代C++编程初体验
任务1:
源代码task1.cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> template<typename T> void output(const T &c); void test1(); void test2(); void test3(); int main() { std::cout << "测试1: \n"; test1(); std::cout << "\n测试2: \n"; test2(); std::cout << "\n测试3: \n"; test3(); } // 输出容器对象c中的元素 template <typename T> void output(const T &c) { for(auto &i : c) std::cout << i << ' '; std::cout << '\n'; } // 测试1:组合使用算法库、迭代器、string反转字符串 void test1() { using namespace std; string s0{"0123456789"}; cout << "s0 = " << s0 << endl; string s1(s0); // 反转s1自身 reverse(s1.begin(), s1.end()); cout << "s1 = " << s1 << endl; string s2(s0.size(), ' '); // 将s0反转后结果拷贝到s2, s0自身不变 reverse_copy(s0.begin(), s0.end(), s2.begin()); cout << "s2 = " << s2 << endl; } // 测试2:组合使用算法库、迭代器、vector反转动态数组对象vector内数据 void test2() { using namespace std; vector<int> v0{2, 0, 4, 9}; cout << "v0: "; output(v0); vector<int> v1{v0}; reverse(v1.begin(), v1.end()); cout << "v1: "; output(v1); vector<int> v2{v0}; reverse_copy(v0.begin(), v0.end(), v2.begin()); cout << "v2: "; output(v2); } // 测试3:组合使用算法库、迭代器、vector实现元素旋转移位 void test3() { using namespace std; vector<int> v0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; cout << "v0: "; output(v0); vector<int> v1{v0}; // 将[v1.begin(), v1.end())区间内元素循环左移1位 rotate(v1.begin(), v1.begin()+1, v1.end()); cout << "v1: "; output(v1); vector<int> v2{v0}; // 将[v1.begin(), v1.end())区间内元素循环左移2位 rotate(v2.begin(), v2.begin()+2, v2.end()); cout << "v2: "; output(v2); vector<int> v3{v0}; // 将[v1.begin(), v1.end())区间内元素循环右移1位 rotate(v3.begin(), v3.end()-1, v3.end()); cout << "v3: "; output(v3); vector<int> v4{v0}; // 将[v1.begin(), v1.end())区间内元素循环右移2位 rotate(v4.begin(), v4.end()-2, v4.end()); cout << "v4: "; output(v4); }
运行结果截图:
关于reverse和reverse_copy的区别
reverse它会直接对容器(比如数组、`vector`等)中的元素进行原地反转操作,也就是说,操作之后,原来的容器里的元素顺序就被改变了,是在原容器上进行修改。
reverse_copy`:它不会改变原来的容器,而是会把原容器中元素反转后的结果复制到另一个指定的容器里。原容器的元素顺序保持不变,新的容器用来存放反转后的元素。
关于rotate算法
改变元素顺序的方式rotate算法的作用是将容器中的元素“旋转”。比如有元素序列[a,b,c,d,e],如果把从某个位置开始的元素旋转到前面,就可能变成[c,d,e,a,b]这样的顺序(具体取决于旋转的位置)。它是通过将容器中一个区间的元素移动到另一个位置,从而整体改变元素的排列顺序。第一个参数表示容器中要进行旋转操作的起始位置的迭代器。第二个参数表示容器中旋转的“枢轴”位置的迭代器,也就是以这个位置为中心来进行旋转操作。第三个参数表示容器中要进行旋转操作的结束位置的迭代器(这个位置的元素不包含在旋转操作内)。
任务2:
源代码
#include <iostream> #include <vector> #include <algorithm> #include <numeric> #include <iomanip> #include <cstdlib> #include <ctime> // 模板函数声明 template<typename T> void output(const T &c); int generate_random_number(); void test1(); void test2(); int main() { std::srand(std::time(0)); // 添加随机种子 std::cout << "测试1: \n"; test1(); std::cout << "\n测试2: \n"; test2(); } // 输出容器对象c中的元素 template <typename T> void output(const T &c) { for(auto &i: c) std::cout << i << ' '; std::cout << '\n'; } // 返回[0, 100]区间内的一个随机整数 int generate_random_number() { return std::rand() % 101; } // 测试1:对容器类对象指定迭代器区间赋值、排序 void test1() { using namespace std; vector<int> v0(10); // 创建一个动态数组对象v0, 对象大小为10 generate(v0.begin(), v0.end(), generate_random_number); // 生成随机数填充v0 cout << "v0: "; output(v0); vector<int> v1{v0}; sort(v1.begin(), v1.end()); // 对整个vector排序 cout << "v1: "; output(v1); vector<int> v2{v0}; sort(v2.begin()+1, v2.end()-1); // 只对中间部分排序,不包含首尾元素 cout << "v2: "; output(v2); } // 测试2:对容器类对象指定迭代器区间赋值、计算最大值/最小值/均值 void test2() { using namespace std; vector<int> v0(10); generate(v0.begin(), v0.end(), generate_random_number); cout << "v0: "; output(v0); // 求最大值和最小值 auto min_iter = min_element(v0.begin(), v0.end()); auto max_iter = max_element(v0.begin(), v0.end()); cout << "最小值: " << *min_iter << endl; cout << "最大值: " << *max_iter << endl; // 同时求最大值和最小值 auto ans = minmax_element(v0.begin(), v0.end()); cout << "最小值: " << *(ans.first) << endl; cout << "最大值: " << *(ans.second) << endl; // 求平均值 double avg1 = accumulate(v0.begin(), v0.end(), 0.0) / v0.size(); cout << "均值: " << fixed << setprecision(2) << avg1 << endl; sort(v0.begin(), v0.end()); double avg2 = accumulate(v0.begin()+1, v0.end()-1, 0.0) / (v0.size()-2); cout << "去掉最大值、最小值之后,均值: " << avg2 << endl; }
运行结果截图
问题1:generate算法的作用是什么?
generate算法的作用是通过调用指定的生成函数,为容器(如vector、数组等中的每个元素生成一个新的值,从而填充或重新生成容器内的元素。
问题2:minmax_element和分别调用min_element、max_element相比有什么优势?
minmax_element可以一次遍历容器就同时找到容器中的最小元素和最大元素的位置,而分别调用min_element和max_element需要两次遍历容器。所以minmax_element的优势是减少了遍历容器的次数,在处理大规模数据时,能提高程序的执行效率。
问题3:把代码中函数generate_random_number`的声明和定义注释起来,把两处调用改成如下写法,观察效果是否等同?查阅C++中lambda表达式用法。
如果原来的generate_random_number函数的功能是返回`std::rand()%101`,那么改成使用lambda表达式`[](){returnstd::rand()%101;};`后,效果是等同的。因为两者都是为`generate`算法提供一个生成随机数(范围在0到100之间)的函数对象。lambda表达式是一种匿名函数,语法形式为`[捕获列表](参数列表)、mutable、异常说明、可返回值类型{函数体}`
任务3:
源代码
#include <iostream> #include <string> #include <algorithm> #include <cctype> unsigned char func(unsigned char c); void test1(); void test2(); int main() { std::cout << "测试1: 字符串大小写转换\n"; test1(); std::cout << "\n测试2: 字符变换\n"; test2(); } unsigned char func(unsigned char c) { if(c == 'z') return 'a'; if(c == 'Z') return 'A'; if(std::isalpha(c)) return static_cast<unsigned char>(c+1); return c; } void test1() { std::string s1{"Hello World 2049!"}; std::cout << "s1 = " << s1 << '\n'; std::string s2; for(auto c: s1) s2 += std::tolower(c); std::cout << "s2 = " << s2 << '\n'; std::string s3; for(auto c: s1) s3 += std::toupper(c); std::cout << "s3 = " << s3 << '\n'; } void test2() { std::string s1{"I love cosmos!"}; std::cout << "s1 = " << s1 << '\n'; std::string s2(s1.size(), ' '); std::transform(s1.begin(), s1.end(), s2.begin(), func); std::cout << "s2 = " << s2 << '\n'; }
运行结果截图
一般来说,自定义函数func`的功能是由开发者根据需求自行定义的。比如可能是对字符进行某种特定转换(如根据某种规则改变字符大小写、替换字符等),或者对传入的参数进行特定计算、逻辑处理等。
tolower和toupper功能
tolower`:用于将一个大写字母字符转换为对应的小写字母字符。如果传入的字符不是大写字母,则返回该字符本身。
toupper`:用于将一个小写字母字符转换为对应的大写字母字符。如果传入的字符不是小写字母,则返回该字符本身。
transform` 的 4 个参数意义
第1个参数:输入范围的起始迭代器,指定要进行转换的元素的起始位置。
第2个参数:输入范围的结束迭代器,指定要进行转换的元素的结束位置(不包含该位置的元素),即转换的范围是 `[起始迭代器, 结束迭代器)`。
第3个参数:输出范围的起始迭代器,指定转换后元素的存储起始位置。
第4个参数:转换函数(或函数对象、lambda 表达式等),用于定义对每个输入元素的转换操作。
把第3个参数s2.begin()`改成s1.begin()的区别
假设s1和s2是两个容器(如`string`等):第3个参数是s2.begin()`时,`transform`会将对s1中元素转换后的结果存储到s2中,`s1`本身的内容不会被修改。当把第3个参数改成s1.begin()时,`transform`会将对s1中元素转换后的结果存储回s1自身,这样会直接修改s1中的元素内容。
任务4:
源代码
#include <iostream> #include <string> #include <algorithm> using namespace std; bool is_palindrome(const string& s) { int left = 0, right = s.size() - 1; while (left < right) { if (s[left] != s[right]) { return false; } left++; right--; } return true; } bool is_palindrome_ignore_case(const string& s) { int left = 0, right = s.size() - 1; while (left < right) { if (tolower(s[left]) != tolower(s[right])) { return false; } left++; right--; } return true; } int main() { string s; // 多组输入,直到按下Ctrl+Z结束测试 while (cin >> s) { cout << "严格区分大小写:" << (is_palindrome(s) ? "true" : "false") << endl; cout << "不区分大小写:" << (is_palindrome_ignore_case(s) ? "true" : "false") << endl; } }
运行结果截图
当使用 cin >> s 输入字符串时,cin 会以空格、制表符或换行符作为字符串的结束标志,所以无法直接输入包含空格的字符串。如果希望输入包含空格的字符串(如 hello oop),可以使用 getline 函数来进行调整
任务5:
源代码
#include <iostream> #include <string> #include <algorithm> std::string dec2n(int x, int n = 2) { if (x == 0) { return "0"; } std::string result; while (x > 0) { int remainder = x % n; char digit; if (remainder < 10) { digit = '0' + remainder; } else { digit = 'A' + remainder - 10; } result = digit + result; x = x / n; } return result; } int main() { int x; while (std::cin >> x) { std::cout << "十进制:" << x << '\n' << "二进制:" << dec2n(x) << '\n' << "八进制:" << dec2n(x, 8) << '\n' << "十二进制:" << dec2n(x, 12) << '\n' << "十六进制:" << dec2n(x, 16) << '\n' << "三十二进制:" << dec2n(x, 32) << "\n\n"; } }
运行结果截图
任务6
源代码
#include <iostream> using namespace std; int main() { for (char c = 'a'; c <= 'z'; c++) { cout << c << " "; } cout << endl; for (int i = 1; i <= 26; i++) { for (char c = 'A' + i - 1; c <= 'Z'; c++) { cout << c << " "; } for (char c = 'A'; c < 'A' + i - 1; c++) { cout << c << " "; } cout << endl; } return 0; }
运行结果截图
任务7
源代码
#include <iostream> #include <cstdlib> #include <ctime> #include <iomanip> using namespace std; int main() { srand(static_cast<unsigned int>(time(0))); int correctCount = 0; const int totalQuestions = 10; for (int i = 0; i < totalQuestions; i++) { int num1 = rand() % 10 + 1; int num2 = rand() % 10 + 1; char op; int opChoice = rand() % 4; if (opChoice == 0) { op = '+'; } else if (opChoice == 1) { op = '-'; if (num1 < num2) { swap(num1, num2); } } else if (opChoice == 2) { op = '*'; } else { op = '/'; num1 = num2 * (rand() % 10 + 1); } int userAnswer, correctAnswer; cout << num1 << " " << op << " " << num2 << " = "; cin >> userAnswer; switch (op) { case '+': correctAnswer = num1 + num2; break; case '-': correctAnswer = num1 - num2; break; case '*': correctAnswer = num1 * num2; break; case '/': correctAnswer = num1 / num2; break; } if (userAnswer == correctAnswer) { correctCount++; } } double accuracy = static_cast<double>(correctCount) / totalQuestions * 100; cout << "正确率:" << fixed << setprecision(2) << accuracy << "%" << endl; return 0; }
运行结果截图