c/c++语言开发共享C++STL快速入门学习

C++ STL中最基本以及最常用的类或容器无非就是以下几个: <! https://blog.csdn.net/laugh12321/article/details/81145439 string vector set list map 下面就依次介绍一下它们,并给出一些最常见的使用方法,做到最快入 …


c++ stl中最基本以及最常用的类或容器无非就是以下几个:

  • string
  • vector
  • set
  • list
  • map

下面就依次介绍一下它们,并给出一些最常见的使用方法,做到最快入门。

string

首先看看我们c语言中一般怎么使用字符串的

 //创建指针指向字符串常量,这段字符串我们是不能修改的 char* s1="hello smartzhou";  //想要创建 可以修改的字符串,我们可以使用数组分配空间 char s2[20]="hello smartzhou"; 或者这样 char s3[ ]="hello smartzhou";  //当然我们也可以动态分配内存 char *s4=(char *)malloc(20*size(char)); gets(s4);

c++标准库中的string表示可变长的字符串,它在头文件string(注意不是string.h)里面。

#include <string>

用string初始化字符串分两类:用”=”就是拷贝初始化,否则就是直接初始化。

C++STL快速入门学习

string s1;                   //初始化字符串,空字符串 string s2=s1;                //拷贝初始化,深拷贝字符串 string s3="hello smartzhou"; //直接初始化,s3存了字符串hello smartzhou string s4(10,'a');           //s4存放的字符串的10个a,即aaaaaaaaaa string s5(s4);               //拷贝初始化,深拷贝字符串 string s6("i am smartzhou"); //直接初始化 string s7=string(6,'c');     //拷贝初始化,s7中6个c,即cccccc 

C++STL快速入门学习

#include <iostream> #include <string> using namespace std;  int main() { string s1;                   //初始化字符串,空字符串 string s2=s1;                //拷贝初始化,深拷贝字符串 string s3="hello smartzhou"; //直接初始化,s3存了字符串hello smartzhou string s4(10,'a');           //s4存放的字符串的10个a,即aaaaaaaaaa string s5(s4);               //拷贝初始化,深拷贝字符串 string s6("i am smartzhou"); //直接初始化 string s7=string(6,'c');     //拷贝初始化,s7中6个c,即cccccc           //string的各种操作     string s8=s3+s6; //将两个字符串合并成一个     s3=s6;                 //将s6中的元素赋值给s3,此时s3="i am smartzhou"      cin>> s1;      cout << s2 << endl;     cout << s3 << endl;     cout << s4 << endl;     cout << s5 << endl;     cout << s6 << endl;     cout << s7 << endl;     cout << s8 << endl;     cout << "s7 size = " << s7.size() << endl; //字符串长度,不包括结束符      cout << (s2.empty() ? "this string is empty" : "this string is not empty") << endl;;       system("pause");     return 0; }

C++STL快速入门学习

string的io操作

使用cin读入字符时,遇到空白就停止读取。比如程序输入的是

"hello    world"

那么我们得到的将是”hello”,hello后面的空格没了,后面的world也读不出来。
如果我们想把整个helo world读进来怎么办?那就这样做

cin>>s1>>s2;

hello存在s1里面,world存入在s2里面了。
有时我们想把一个句子存下来,又不想像上面那样创建多个string来存储单词,怎么办?
那就是用getline来获取一整行内容。

string str; getline(cin,str); cout<<str<<endl;

当把string对象和字符变值及字符串面值混在一条语句中使用时,必须确保+的两侧的运算对象至少有一个是string

string s1=s2+"hello world";  //正确 string s3="s"+"hello world"  //错误 string s4="hello"+"world"+s1;//错误 string s5=s1+“hello”+"world";//正确 上面式子改一下顺序,s1放前面,就正确了,注意理解=号右边的运算顺序 
  • 未完待续 c/c++开发分享C++STL快速入门学习后续更新

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/606254.html

(0)
上一篇 2021年5月13日
下一篇 2021年5月13日

精彩推荐