当前位置: 首页 > news >正文

C++函数与string对象、array对象及递归详解

C++函数与string对象、array对象及递归详解

一、string对象的数组操作

string对象比C风格字符串更灵活,可以像结构体一样进行赋值和传递。以下示例展示了string数组的用法:

#include<iostream>#include<string>usingnamespacestd;constintSIZE=5;voiddisplay(conststring sa[],intn);intmain(){string list[SIZE];cout<<"Enter your "<<SIZE<<" favorite astronomical sights:\n";for(inti=0;i<SIZE;i++){cout<<i+1<<": ";getline(cin,list[i]);}cout<<"\nYour list:\n";display(list,SIZE);return0;}voiddisplay(conststring sa[],intn){for(inti=0;i<n;i++)cout<<i+1<<": "<<sa[i]<<endl;}

关键点:

  • string对象数组声明:string list[SIZE];
  • 每个元素都是完整的string对象
  • 可以像基本类型一样操作

二、array对象的函数参数传递

C++11的array模板类提供了更好的数组安全性:

#include<iostream>#include<array>#include<string>constintSeasons=4;constarray<string,Seasons>Snames={"Spring","Summer","Fall","Winter"};// 按值传递(用于显示)voidshow(array<double,Seasons>da);// 按地址传递(用于修改)voidfill(array<double,Seasons>*pa);intmain(){array<double,Seasons>expenses;fill(&expenses);// 传递地址show(expenses);// 传递值(副本)return0;}voidfill(array<double,Seasons>*pa){usingnamespacestd;for(inti=0;i<Seasons;i++){cout<<"Enter "<<Snames[i]<<" expenses: ";cin>>(*pa)[i];// 注意解引用语法}}voidshow(array<double,Seasons>da){usingnamespacestd;doubletotal=0.0;cout<<"\nEXPENSES\n";for(inti=0;i<Seasons;i++){cout<<Snames[i]<<": $"<<da[i]<<endl;total+=da[i];}cout<<"Total expenses: $"<<total<<endl;}

重要区别:

  • show(expenses):按值传递,操作副本
  • fill(&expenses):按地址传递,操作原始数据

三、递归函数详解

1. 单递归调用

#include<iostream>usingnamespacestd;voidcountdown(intn);intmain(){countdown(4);return0;}voidcountdown(intn){cout<<"Counting down ... "<<n<<endl;if(n>0)countdown(n-1);// 递归调用cout<<n<<": Kaboom!\n";}

输出分析:

Counting down ... 4 (第1层调用,n=4) Counting down ... 3 (第2层调用,n=3) Counting down ... 2 (第3层调用,n=2) Counting down ... 1 (第4层调用,n=1) Counting down ... 0 (第5层调用,n=0) 0: Kaboom! (第5层返回) 1: Kaboom! (第4层返回) 2: Kaboom! (第3层返回) 3: Kaboom! (第2层返回) 4: Kaboom! (第1层返回)

递归特点:

  • 每次调用创建独立的变量副本
  • 递归深度有限制(通常受栈空间限制)
  • 必须有终止条件(否则无限递归)

2. 多递归调用(分而治之)

#include<iostream>constintLen=66;constintDivs=6;voidsubdivide(charar[],intlow,inthigh,intlevel);intmain(){charruler[Len];// 初始化标尺for(inti=1;i<Len-2;i++)ruler[i]=' ';ruler[Len-1]='\0';ruler[0]=ruler[Len-2]='|';std::cout<<ruler<<std::endl;// 递归细分for(inti=1;i<=Divs;i++){subdivide(ruler,0,Len-2,i);std::cout<<ruler<<std::endl;// 重置中间标记(准备下一轮)for(intj=1;j<Len-2;j++)ruler[j]=' ';}return0;}voidsubdivide(charar[],intlow,inthigh,intlevel){if(level==0)// 终止条件return;intmid=(high+low)/2;ar[mid]='|';// 左右分别递归subdivide(ar,low,mid,level-1);subdivide(ar,mid,high,level-1);}

输出特点:

  • 每次递归将当前段分为两半
  • 分治策略的典型应用
  • 可用于绘制标尺、二分查找等场景

四、最佳实践建议

  1. string vs C风格字符串

    • 优先使用string,更安全方便
    • string对象自动管理内存
  2. array vs 原生数组

    • array知道自身大小(size()方法)
    • 更好的类型安全性
    • 支持迭代器操作
  3. 递归使用注意事项

    // 正确示例:有明确终止条件intfactorial(intn){if(n<=1)return1;// 终止条件returnn*factorial(n-1);// 递归调用}// 错误示例:缺少终止条件(无限递归)voidinfinite(){infinite();// 危险!}
  4. 递归优化

    • 深度过大可能导致栈溢出
    • 考虑尾递归优化或迭代替代
    • 使用备忘录(memoization)避免重复计算

五、总结

本文介绍了C++中三类重要的编程技术:string对象数组操作、array模板类的函数参数传递,以及递归函数的原理和应用。掌握这些技术能让你:

  • 更安全地处理字符串和数组
  • 理解值传递和地址传递的区别
  • 掌握递归思维,解决分治类问题

递归虽强大,但需谨慎使用。确保有明确的终止条件,并注意递归深度限制。对于性能敏感的场景,考虑使用迭代替代递归。

http://www.jsqmd.com/news/166359/

相关文章:

  • 变速精灵下载安装教程:原理解析、实用步骤与使用经验总结 - PC修复电脑医生
  • 解决LLM返回JSON格式错误的3大技巧
  • 淄博抖音代运营公司哪家更靠谱?2025年终7家服务商权威评测与最终推荐! - 品牌推荐
  • 在CI/CD流水线中使用Miniconda-Python3.9自动构建PyTorch环境
  • 怎么通过 企业版的 google api 调用LLM gemini3
  • 感知机(感知机的局限性)
  • sourcefare速成手册(2) - 使用Git方式克隆代码代码扫描
  • Miniconda-Python3.9如何帮助团队统一PyTorch开发规范
  • 分布式锁与重试机制标准化方案
  • REDMI Note 15 Pro新春版车厘子红全方位外观公布 高级氛围感拉满
  • 在有网Windows机器A上使用conda-pack打包虚拟环境,然后迁移到无网Windows机器B
  • 感知机的致命缺陷:为什么它连简单的异或问题都解决不了?
  • PyTorch故障注入测试:Miniconda-Python3.9环境模拟异常
  • PyTorch缓存机制优化:基于Miniconda-Python3.9环境测试
  • NVIDIA Container Toolkit 安装
  • 使用Miniconda-Python3.9搭建BERT文本分类PyTorch实验环境
  • Miniconda-Python3.9环境下使用TorchScript保存和加载模型
  • 华为OD机试双机位C卷 - 魔法收积木 (C++ Python JAVA JS GO)
  • 【vLLM 学习】Reproduciblity
  • Miniconda-Python3.9环境下批量安装常用AI库(PyTorch/TensorFlow/scikit-learn)
  • Java对象头(Object Header)
  • PyTorch DataLoader性能瓶颈排查:从Miniconda环境入手
  • 2025年AI行业热点:应用层核心技术人才年薪破百万,字节跳动、腾讯等巨头争相布局黄金赛道!
  • PyTorch Geometric等扩展库在Miniconda-Python3.9中的安装方法
  • PyTorch自定义算子开发环境搭建:Miniconda-Python3.9指南
  • 「地质约束显式+数据驱动模型」的新路径,浙江大学团队实现跨区域矿产远景预测性能和可解释性提升
  • PyTorch批处理任务调度:Miniconda-Python3.9环境自动化脚本
  • Miniconda-Python3.9结合Markdown编写可执行AI技术文档
  • PyTorch QoS保障机制:基于Miniconda-Python3.9环境实现
  • 2025年AI领域全景观察:从大模型突破到Agent架构,开发者必读的技术趋势指南!