初步理解STL
STL(Standard Template Library,标准模板库)是惠普实验室开发的一系列软件的统称。
STL的从广义上讲分为三类:algorithm(算法)、container(容器)和iterator(迭代器),容器和算法通过迭代器可以进行无缝地连接。几乎所有的代码都采 用了模板类和模板函数的方式,这相比于传统的由函数和类组成的库来说提供了更好的代码重用机会。
**优点:**STL是C++的一部分,它被内建在你的编译器之内。STL的一个重要特点是数据结构和算法的分离,使得STL变得非常通用。
STL具有高可重用性,高性能,高移植性,跨平台的优点。
STL六大组件:
容器(Container)
算法(Algorithm)
迭代器(Iterator)
仿函数(Function object)
适配器(Adaptor)
Subtopic
空间配制器(allocator)
容器
在数据存储上,有一种对象类型,它可以持有其它对象或指向其它对象的指针,这种对象类型就叫做容器。
通俗理解就是各种数据结构(数组、链表、栈、队列、树……)的封装。
迭代器
软件设计有一个基本原则,所有的问题都可以通过引进一个间接层来简化, 这种简化在STL中就是用迭代器来完成的。概括来说,迭代器在STL中用来将算法和容器联系起来,起着一种黏和剂的作用。几乎STL提供的所有算法都是通 过迭代器存取元素序列进行工作的,每一个容器都定义了其本身所专有的迭代器,用以存取容器中的元素。
容器:string
string是STL的字符串类型,通常用来表示字符串。string与char*都可以用来表示字符串,那么二者有什么区别呢。
1、string是一个类, char*是一个指向字符的指针。string封装了char*,管理这个字符串,是一个char*型的容器。
2、string不用考虑内存释放和越界。string管理char*所分配的内存。每一次string的复制,取值都由string类负责维护,不用担心复制越界和取值越界等。
3、string提供了一系列的字符串操作函数,查找find,拷贝copy,删除erase,替换replace,插入insert等
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
// string构造
void func1()
{
string str1 = "hello world";
string str2("llowo");
string str3 = str2; //拷贝构造
string str4(10, 'h');
cout << str1 << endl; //结果:hello world
cout << str2 << endl; //结果:llowo
cout << str3 << endl; //结果:llowo
cout << str4 << endl; //结果:hhhhhhhhhh
}
// string 遍历
void func2()
{
string str = "hello world";
str[1] = 'E';
// 1、通过数组下标
for (unsigned int i = 0; i < str.length(); i++)
{
cout << str[i]; //结果:hEllo world
}
cout << endl;
// 2、string 也有迭代器
for (string::iterator it = str.begin(); it != str.end(); it++)
{
cout << *it; //结果:hEllo world
}
cout << endl;
// 3、通过 at(数组下标) 函数来访问
for (unsigned int i = 0; i < str.length(); i++)
{
cout << str.at(i); //结果:hEllo world
}
cout << endl;
}
// string 和 char *的转换
void func3()
{
string str = "hello world";
// string -----> char *
printf ("str = %s\n", str.c_str()); //结果:str = hello world
}
// 字符串的连接
void func4()
{
string str1 = "Hello";
string str2 = str1 + " world!";
cout << str2 << endl; //结果:str = Hello world!
}
// 查找和替换
void func5()
{
string str = "111 he 222 he 3333 he 44444 he 555555555 he";
int index = 0;
index = str.find("he", index);
while (index != string::npos)
{
cout << index++ << endl; //结果:4
index = str.find("hello", index);
}
// 将所有he替换成 HE
index = 0;
index = str.find("he", index);
while (index != string::npos)
{
str.replace(index, 2, "HE");
index = str.find("he", index);
}
cout << str << endl; //结果:111 HE 222 HE 3333 HE 44444 HE 555555555 HE
}
// 删除和插入
void func6()
{
string str = "hello world";
// 通过迭代器删除
str.erase(str.begin());
cout << str << endl; //结果:ello world
// 区间删除
str.erase(str.begin(), str.begin()+7);
cout << str << endl; //结果:rld
// 全部删除:删除是 左闭右开的 [str.begin(), str.end())
str.erase(str.begin(), str.end());
cout << str << endl; //结果:
str = "hello world";
// 从 下标 2 开始删除 4 个字符
str.erase(2, 4);
cout << str << endl; //结果:heworld
}
int main()
{
//func1();
//func2();
//func3();
//func4();
//func5();
func6();
return 0;
}