由find_char()函数所想到的
来源:互联网 发布:淘宝店铺显示未开店 编辑:程序博客网 时间:2024/05/21 18:41
题目:定义一个find_char的函数,它返回在string对象中某个指定字符第一次出现的位置,同时返回该字符出现的总次数。(C++primer第五版P189)
参照书上的程序,将答案完整了一下。
#include<iostream>#include<string>using namespace std;string::size_type find_char(const string &str,char ch,string::size_type &cnt) //int类型改为size_type{ auto pos = str.size(); for(decltype(pos) i=0;i!=str.size();++i) { if(str[i] == ch) { if(pos == str.size()) pos =i; ++cnt; } } return pos;}int main(){ string str; size_t cnt = 0; cout<<"Please input one string: "<<endl; cin>>str; cout<<"The string "<<str<<" has "<<str.size()<<" letters."<<endl; //统计字符串字母的个数 char ch; cout<<"Please input the char you want to find : "<<endl; cin>>ch; auto pos = find_char(str,ch,cnt); cout<<"The ch "<<ch<<" first appears at the "<<pos+1<<" position"<<endl; cout<<"The ch "<<ch<<" appears "<<cnt<<" times."<<endl; system("pause"); return 0;}
在编程的过程中遇到的一些问题,总结如下:
1、string::size_type前面必须加string::,否则会报错;
2、string::size_type也可以用int类型,但推荐用string::size_type,因为移植性好;
3、find_char()函数中第一个变量const string &str中的const也可以去掉,考虑“如果函数无需改变引用形参的值,最好将其声明为常量引用”,因此还是加上const;
4、关于decltype的用法见c++11新特性–decltype;
5、STL = Standard Template Library,标准模板库,惠普实验室开发的一系列软件的统称。它是由Alexander Stepanov、Meng Lee和David R Musser在惠普实验室工作时所开发出来的。从根本上说,STL是一些“容器”的集合,这些“容器”有list,vector,set,map等,STL也是算法和其他一些组件的集合。STL的目的是标准化组件,这样就不用重新开发,可以使用现成的组件;
6、通过如下形式调用函数:auto pos = find_char(str,ch,cnt);
7、sizeof()和size(),区分见我的下一篇博客sizeof()、size()、strlen()总结。
0 0
- 由find_char()函数所想到的
- 由体育所想到的
- 由CreateInstance所想到的......
- 由'\\n'所想到的
- 由“多音字”所想到的
- 由 Runtime 所想到的
- 由assert的定义所想到的
- 由《罗素的故事》所想到的
- 由三层加架构所想到的
- 由安装宽带所想到的
- 由软件升级所想到的
- 【原创】由分水所想到的
- 由挂机程序所想到的!
- 由超图上市所想到的
- 由超图上市所想到的
- 由FoxMail导入联系人所想到的。。
- 由百度暴富所想到的
- 由一道Python题所想到的
- Auto Layout Process 自动布局过程
- [LeetCode][动态规划]House Robber
- 快速排序详解
- uva 12034 Race
- Object-C基础(3)—— 流程控制与数组
- 由find_char()函数所想到的
- Socket 端口的限制
- Cocos2d-x笔记记忆整理Day6-绘图原理及优化
- Codeforces 652 B. z-sort
- 批次查找原理
- Android学习笔记--监听按钮的点击事件
- 抽象类与 接口
- 决策树
- MotionEvent中getX()和getRawX()的区别