由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
原创粉丝点击