卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章76281本站已运行4320

在 C++ 中使用自身函数解决常见问题

c++++ 标准库中内置函数可解决常见问题,包括:字符串操作:toupper 和 tolower 用于大小写转换strcmp 用于字符串比较数值处理:abs 获取绝对值rand 生成随机数数组操作:find 查找元素sort 对数组排序

在 C++ 中使用自身函数解决常见问题

在 C++ 中使用自身函数解决常见问题

C++ 标准库提供了许多有用的函数来解决常见问题,通过利用这些函数,你可以写出更简洁、更可读的代码。本文将介绍几个使用自身函数解决常见问题的实用示例。

字符串操作

立即学习“C++免费学习笔记(深入)”;

  • 转换为大写/小写:toupper 和 tolower 函数可以将字符串中的字符转换为大写和小写。

    #include <iostream>
    #include <string>
    
    int main() {
    std::string str = "Hello, World!";
    std::cout << "Original string: " << str << std::endl;
    std::cout << "Uppercase: " << toupper(str) << std::endl;
    std::cout << "Lowercase: " << tolower(str) << std::endl;
    return 0;
    }
  • 比较字符串:strcmp 函数比较两个字符串,返回一个整数,表示它们之间的关系。

    #include <iostream>
    #include <cstring>
    
    int main() {
    const char *str1 = "C++";
    const char *str2 = "Python";
    int result = strcmp(str1, str2);
    if (result > 0) {
      std::cout << "str1 is greater than str2" << std::endl;
    } else if (result == 0) {
      std::cout << "str1 is equal to str2" << std::endl;
    } else {
      std::cout << "str1 is less than str2" << std::endl;
    }
    return 0;
    }

数值处理

  • 绝对值:abs 函数返回一个给定整数或浮点数的绝对值。

    #include <iostream>
    #include <cstdlib>
    
    int main() {
    int num1 = 10;
    int num2 = -20;
    std::cout << "Absolute value of " << num1 << ": " << abs(num1) << std::endl;
    std::cout << "Absolute value of " << num2 << ": " << abs(num2) << std::endl;
    return 0;
    }
  • 随机数:rand 函数生成一个伪随机整数。

    #include <iostream>
    #include <cstdlib>
    
    int main() {
    // 初始化随机种子
    srand(time(NULL));
    // 生成一个 0 到 100 之间的随机整数
    int random_number = rand() % 100 + 1;
    std::cout << "Random number: " << random_number << std::endl;
    return 0;
    }

数组操作

  • 查找元素:find 算法在数组中搜索一个元素,并返回其迭代器。

    #include <iostream>
    #include <algorithm>
    
    int main() {
    int arr[] = {1, 3, 5, 7, 9};
    int element_to_find = 5;
    std::vector<int>::iterator it = std::find(arr, arr + 5, element_to_find);
    if (it != arr + 5) {
      std::cout << "Element found at index: " << it - arr << std::endl;
    } else {
      std::cout << "Element not found" << std::endl;
    }
    return 0;
    }
  • 排序数组:sort 算法对数组进行排序。

    #include <iostream>
    #include <algorithm>
    
    int main() {
    int arr[] = {1, 5, 3, 7, 9};
    std::sort(arr, arr + 5);  // 升序排序
    for (int i = 0; i < 5; i++) {
      std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
    }
卓越飞翔博客
上一篇: C++ 函数调用约定与栈帧管理的常见问题与解决方案
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏