C++进阶(语法篇)—第9章 STL

本文深入讲解C++中的STL,重点介绍了顺序容器,包括string、vector、array、deque和list的初始化、迭代器和常用操作。通过实例代码演示了各种容器的使用方法,如string的构造函数、迭代器遍历,vector的插入删除操作,array的基本操作以及deque和list的双端操作。这些内容对于理解和应用STL至关重要。
摘要由CSDN通过智能技术生成

9 STL

9.1标准模板库

三大编程理念:过程化编程、对象化编程和泛型编程。标准模板库STL运用的就是泛型编程的思想,将算法独立于数据类型之外,强调了代码的重用技术。

STL是每一个C++程序员必须掌握的技术,其分为3部分:容器、迭代器、算法。

容器是存放同类数据的一种数据结构,如数组、队列、链表等。容器可以分为3大类:顺序容器、关联容器、容器适配器。迭代器用来遍历容器中的对象。算法是对容器对象的各种操作,如插入、删除、搜索、排序等。

9.2顺序容器

顺序容器包括string、vector、array、deque、list等。

9.2.1 string

标准库string可以用来存储不定长度的字符串,使用string需要包含头文件string和使用名称空间std。

//string初始化

#include <iostream>

#include <string>

 

using namespace std;

 

 

int main(int argc, char ** argv)

{

//简单的初始化

string s1; //s1初始化为空字符串

string s2("hello"); //s2用C-风格字符串来初始化,等价于string s2 = "hello"

char ar[] = { "array"};

string s3(ar); //s3用字符数组来初始化,等价于string s3 = ar

const char * cp = "character pointer";

string s4(cp); //s4用字符指针来初始化,等价于string s4 = cp

string s5(s2); //s5用string对象来初始化,等价于string s5 = s2

 

//初始化进阶

string s6(5, 'a'); //用5个字符'a'来初始化s6

string s7("hello world",5); //取前5个字符来初始化s7

string s8(s4,10,7); //从s4的下标10开始,拷贝7个字符

string s9(s8.begin(), s8.end());//用s8的迭代器来初始化s9

 

cout << s1 << endl << s2 << endl << s3 << endl << s4 << endl << s5 << endl << s6 << endl << s7 << endl << s8 << endl << s9 << endl;

 

return 0;

}

运行结果:

 

hello

array

character pointer

hello

aaaaa

hello

pointer

pointer

在以前的string类中,介绍了6种方法来初始化string对象,在这里又介绍3种。我们学习了类,知道string本质上是一个类,其初始化时调用string的构造函数。那么string s2("hello")和string s2 = "hello"又有什么区别呢?

string s2("hello")是调用string的有参构造函数,string s2 = "hello"调用的是string类的拷贝构造函数。2种方法都可以用来初始化string对象,但是为了统一,以后都采用第一种方法。

//string迭代器

#include <iostream>

#include <string>

 

using namespace std;

 

 

int main(int argc, char ** argv)

{

string s1("hello");

s1 += " world!";

string::iterator start = s1.begin();

string::iterator end = s1.end();

for (; start != end; start++)

{

cout << *start;

}

 

cout<< endl;

const string s2("hello China!");//字符串只读

string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值