• C++ 学习(17)STL - vector容器、string容器


    1、STL

    STL(Standard Template Library)标准模板库,是C++为建立 数据结构与算法的一套标准。STL从广义上分为:容器(container)、算法(algorithm)、迭代器(iterator),容器和算法之间通过迭代器进行无缝连接。STL几乎所有的代码都采用了类模板或者函数模板。

    1.1、STL六大组件

    容器、算法、迭代器、仿函数、适配器(配接器)、空间配置器

    1. 容器:各种数据结构,如vector、list、deque、set、map等,用来存放数据
    2. 算法:各种常用的算法,如sort、find、copy、for_each等
    3. 迭代器:扮演了容器与算法之间的粘合剂
    4. 仿函数:行为类似函数,可作为算法的某种策略
    5. 适配器:一种用来修饰容器或者仿函数或迭代器接囗的东西
    6. 空间配置器:负责空间的配置与管理

    (1)容器(置物之所也)

    STL容器就是将运用最广泛的一些数据结构实现出来,常用的数据结构包含:数组、链表、树、栈、队列、集合、映射表等;这些容器分为序列式容器与关联式容器两种:

    • 序列式容器:强调值的排序,序列式容器中的每个元素均有固定的位置
    • 关联式容器:二叉树结构,各元素之间没有严格的物理上的顺序关系

    (2)算法(问题之解法也)

    有限的步骤解决逻辑或数学上的问题,这一门学科叫做算法。算法分为质变算法与非质变算法:

    • 质变算法:是指运算过程中会更改区间内的元素的内容,如拷贝、替换、删除等
    • 非质变算法:是指运算过程中不会更改区间内的元素内容,如查找、计数、遍历、寻找极值等

    (3)迭代器(容器和算法之间的粘合剂)

    提供一种方法,使用之能够依序寻访某个容器所含的各个元素,而又无需暴露该容器的内部表示方式。每个容器都有自己专属的迭代器。迭代器使用非常类似于指针,初学阶段也可以先将迭代器理解为指针。迭代器种类划分五种:

    • 输入迭代器: 对数据只读访问,支持++、==、!=
    • 输出迭代器:对数据只写访问,支持++
    • 前向迭代器:读写操作,并能向前推进迭代器,支持++、==、!=
    • 双向迭代器:读写操作,并能向前和向后操作,支持++、--
    • 随机访问迭代器:读写操作,可以心跳跃的方式访问任意数据,功能最强的迭代器,支持++、--、[n]、-n、<、<=、>、>=

    2、vector容器

    STL中最常用的容器为vector,vector数据结构与数组非常相似,也称为单端数组。

    vector与普通数组的区别在于数组是静态空间,而vector可以动态扩展。所谓动态扩展,并不是在原空间之后维埃拉新空间,而是找更大的内存空间,然后将原数据拷贝至新空间中,释放原空间。

    vector容器的迭代器是支持随机访问的迭代器。

    容器:vector

    算法:for_each

    迭代器:vector::iterator

    2.1、vector构造函数

    函数原型:

    • vector v;                        //采用模板实现类,默认构造函数
    • vector(v.begin(), v.end());    //将v[begin(), end()]区间中的元素拷贝给其本身
    • vecotr(n, elem);                  //构造函数将n个elem拷贝给本身
    • vector(const vector& vec); //拷贝构造函数
    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. void print(vector<int>& v)
    6. {
    7. for (int i = 0; i < v.size(); i++)
    8. {
    9. cout << v[i] << "\t";
    10. }
    11. cout << endl;
    12. }
    13. int main()
    14. {
    15. // STL - vector - 构造函数
    16. /*函数原型:
    17. 1、vector v;                        //采用模板实现类,默认构造函数
    18. 2、vector(v.begin(), v.end());    //将v[begin(), end()]区间中的元素拷贝给其本身
    19. 3、vecotr(n, elem);                  //构造函数将n个elem拷贝给本身
    20. 4、vector(const vector& vec); //拷贝构造函数
    21. */
    22. //1、vector v; 
    23. vector<int> v1;
    24. //赋值
    25. for (int i = 0; i < 5; i++)
    26. {
    27. v1.push_back(i + 1);
    28. }
    29. //显示
    30. print(v1);
    31. //2、vector(v.begin(), v.end());
    32. vector<int> v2(v1.begin(), v1.end());
    33. print(v2);
    34. //3、vecotr(n, elem);   
    35. vector<int> v3(3,8);
    36. print(v3);
    37. //4、vector(const vector& vec);
    38. vector<int> v4(v1);
    39. print(v4);
    40. system("pause");
    41. return 0;
    42. }

    输出结果

    1       2       3       4       5
    1       2       3       4       5
    8       8       8
    1       2       3       4       5

    2.2、vector赋值操作

    函数原型:

    • vector& operator=(const vector &vec);  //重载=运算符
    • assign(beg, end);      //将[beg, end)区间中的数据拷贝赋值给本身
    • assign(n, elem);        //将n个elem拷贝赋值给本身
    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. void print(vector<int>& v)
    6. {
    7. for (int i = 0; i < v.size(); i++)
    8. {
    9. cout << v[i] << "\t";
    10. }
    11. cout << endl;
    12. }
    13. int main()
    14. {
    15. // STL - vector - 赋值操作
    16. /*函数原型:
    17. 1、vector& operator=(const vector &vec);  //重载=运算符
    18. 2、assign(beg, end);      //将[beg, end)区间中的数据拷贝赋值给本身
    19. 3、assign(n, elem);        //将n个elem拷贝赋值给本身
    20. */
    21. vector<int> v1;
    22. for (int i = 0; i < 5; i++)
    23. {
    24. v1.push_back(i + 1);
    25. }
    26. //1、vector& operator=(const vector &vec);
    27. vector<int> v2;
    28. v2 = v1;
    29. print(v2);
    30. //2、assign(beg, end); 
    31. vector<int> v3(v1.begin(), v1.end());
    32. print(v3);
    33. //3、assign(n, elem); 
    34. vector<int> v4;
    35. v4.assign(3, 8);
    36. print(v4);
    37. system("pause");
    38. return 0;
    39. }

    输出结果

    1       2       3       4       5
    1       2       3       4       5
    8       8       8

    2.3、vector容量和大小

    函数原型

    • empty();                        //判断容器是否为空
    • capacity();                    //容器容量
    • size();                          //返回容器中元素个数
    • resize(int num);          //重新指定窗口的长度为num,若容器变长,则以默认值填充新位置,如果变短,则末尾超出容器长度的元素被删除。
    • resize(int num, elem); //重新指定容器长度的num,基容器变长,则以elem值填充新位置;如果变短,则末尾超出容器长度的元素被删除。
    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. void print(vector<int>& v)
    6. {
    7. for (int i = 0; i < v.size(); i++)
    8. {
    9. cout << v[i] << "\t";
    10. }
    11. cout << endl;
    12. }
    13. int main()
    14. {
    15. // STL - vector - 赋值操作
    16. /*函数原型:
    17. 1、empty();               //判断容器是否为空
    18. 2、capacity();            //容器容量
    19. 3、size();                //返回容器中元素个数
    20. 4、resize(int num);       //重新指定窗口的长度为num,若容器变长,则以默认值填充新位置,如果变短,则末尾超出容器长度的元素被删除。
    21. 5、resize(int num, elem); //重新指定容器长度的num,基容器变长,则以elem值填充新位置;如果变短,则末尾超出容器长度的元素被删除。
    22. */
    23. //1、empty(); 
    24. vector<int> v1;
    25. cout << "1、容器是否为空:" << (v1.empty() ? "容器为空" : "容器不为空") << endl;
    26. for (int i = 0; i < 5; i++)
    27. {
    28. v1.push_back(i + 1);
    29. }
    30. cout << "1、容器是否为空:" << (v1.empty() ? "容器为空" : "容器不为空") << endl;
    31. cout << "1、容器元素:" << endl;
    32. print(v1);
    33. //2、capacity();
    34. cout << "2、容器容量:" << v1.capacity() << endl;
    35. //3、size(); 
    36. cout << "3、容器中元素个数:" << v1.size() << endl;
    37. //4、resize(int num);
    38. v1.resize(7);
    39. cout << "4、容器长度变长后元素:" << endl;
    40. print(v1);
    41. v1.resize(4);
    42. cout << "4、容器长度变短后元素:" << endl;
    43. print(v1);
    44. //5、resize(int num, elem);
    45. v1.resize(7, 8);
    46. cout << "5、容器长度变长后元素:" << endl;
    47. print(v1);
    48. v1.resize(5);
    49. cout << "5、容器长度变短后元素:" << endl;
    50. print(v1);
    51. system("pause");
    52. return 0;
    53. }

    输出结果

    1、容器是否为空:容器为空
    1、容器是否为空:容器不为空
    1、容器元素:
    1       2       3       4       5
    2、容器容量:6
    3、容器中元素个数:5
    4、容器长度变长后元素:
    1       2       3       4       5       0       0
    4、容器长度变短后元素:
    1       2       3       4
    5、容器长度变长后元素:
    1       2       3       4       8       8       8
    5、容器长度变短后元素:
    1       2       3       4       8

    2.4、vector插入与删除

    函数原型

    插入元素

    • push_back(ele);                         //尾部插入元素
    • insert(const_iterator pos, ele);  //迭代器指向位置pos插入元素ele
    • insert(const_iterator pos, int count, ele);  //迭代器指向位置pos插入count个元素ele

    删除元素

    • pop_back();                           //删除最后一个元素
    • erase(const_iterator pos);    //删除迭代器指向的元素
    • earse(const_iterator start, const_iterator end);  //删除迭代器从start到end之间的元素
    • clear();                                 //删除容器中所有元素 
    1. #include
    2. #include
    3. using namespace std;
    4. void print(vector<int>& v)
    5. {
    6. for (int i = 0; i < v.size(); i++)
    7. {
    8. cout << v[i] << "\t";
    9. }
    10. cout << endl;
    11. }
    12. int main()
    13. {
    14. // STL - vector - 插入和删除
    15. /*函数原型
    16. 插入元素:
    17. 1、push_back(ele);                //尾部插入元素
    18. 2、insert(const_iterator pos, ele);  //迭代器指向位置pos插入元素ele
    19. 3、insert(const_iterator pos, int count, ele);  //迭代器指向位置pos插入count个元素ele
    20. 删除元素:
    21. 4、pop_back();                      //删除最后一个元素
    22. 5、erase(const_iterator pos);    //删除迭代器指向的元素
    23. 6、earse(const_iterator start, const_iterator end);  //删除迭代器从start到end之间的元素
    24. 7、clear();         //删除容器中所有元素
    25. */
    26. vector<int> v1;
    27. //1、2、3 插入元素; 
    28. v1.push_back(20);
    29. cout << "1、插入元素后:";
    30. print(v1);
    31. v1.insert(v1.begin(), 32);
    32. cout << "2、插入元素后:";
    33. print(v1);
    34. v1.insert(v1.begin(), 3,50);
    35. cout << "3、插入元素后:";
    36. print(v1);
    37. //4、5、6、7 删除元素;   
    38. v1.pop_back();
    39. cout << "4、删除元素后:";
    40. print(v1);
    41. v1.erase(v1.begin());
    42. cout << "5、删除元素后:";
    43. print(v1);
    44. v1.erase(v1.begin(), v1.end());
    45. cout << "6、删除元素后:";
    46. print(v1);
    47. v1.insert(v1.begin(), 3, 50);
    48. cout << "3、插入元素后:";
    49. print(v1);
    50. v1.clear();
    51. cout << "7、删除元素后:";
    52. print(v1);
    53. system("pause");
    54. return 0;
    55. }

    输出结果

    1、插入元素后:20
    2、插入元素后:32       20
    3、插入元素后:50       50      50      32      20
    4、删除元素后:50       50      50      32
    5、删除元素后:50       50      32
    6、删除元素后:
    3、插入元素后:50       50      50
    7、删除元素后:

    2.5、vector数据读取

    函数原型

    • at(int idx);   //返回索引idx所指向的数据
    • operator[];  //返回索引idx所指向的数据
    • front();       //返回容器中第一个数据元素
    • back();      //返回容器中最后一个数据元素
    1. #include
    2. #include
    3. using namespace std;
    4. void print(vector<int>& v)
    5. {
    6. for (int i = 0; i < v.size(); i++)
    7. {
    8. cout << v[i] << "\t";
    9. }
    10. cout << endl;
    11. }
    12. int main()
    13. {
    14. // STL - vector - 数据读取
    15. /*函数原型
    16. 1、at(int idx); //返回索引idx所指向的数据
    17. 2、operator[];  //返回索引idx所指向的数据
    18. 3、front();     //返回容器中第一个数据元素
    19. 4、back();      //返回容器中最后一个数据元素
    20. */
    21. vector<int> v1;
    22. for (int i = 0; i < 5; i++)
    23. {
    24. v1.push_back(i * 5);
    25. }
    26. cout << "容器中的元素:";
    27. print(v1);
    28. //1、at(int idx);
    29. cout << "1、读取第1个元素:" << v1.at(0) << endl;
    30. //2、operator[];
    31. cout << "2、读取第2个元素:" << v1[1] << endl;
    32. //3、front();
    33. cout << "3、读取容器中第1个元素:" << v1.front() << endl;
    34. //4、back(); 
    35. cout << "4、读取容器中最后1个元素:" << v1.back() << endl;
    36. system("pause");
    37. return 0;
    38. }

    输出结果

    容器中的元素:0 5       10      15      20
    1、读取第1个元素:0
    2、读取第2个元素:5
    3、读取容器中第1个元素:0
    4、读取容器中最后1个元素:20

    2.6、vector互换容器

    可以巧妙使用互换容器收缩内存空间,使用vector匿名对象与当前vector互换容器,匿名对象特点是当前执行完,编译器立即回收内存空间,因此互换后之间的空间被释放了。

    函数原型

    • swap(vec);  //将vec与本身的元素互换
    1. #include
    2. #include
    3. using namespace std;
    4. void print(vector<int>& v)
    5. {
    6. for (int i = 0; i < v.size(); i++)
    7. {
    8. cout << v[i] << "\t";
    9. }
    10. cout << endl;
    11. }
    12. int main()
    13. {
    14. // STL - vector - 互换容器
    15. /*函数原型
    16. swap(vec);  //将vec与本身的元素互换
    17. */
    18. vector<int> v1;
    19. for (int i = 0; i < 5; i++)
    20. {
    21. v1.push_back(i * 5);
    22. }
    23. cout << "交换前,v1 容器中的元素:";
    24. print(v1);
    25. cout << "交换前,v1 容器容量:" << v1.capacity() << ", 容器大小:" << v1.size() << endl;
    26. vector<int> v2;
    27. for (int i = 0; i < 7; i++)
    28. {
    29. v2.push_back(i + 5);
    30. }
    31. cout << "交换前,v2 容器中的元素:";
    32. print(v2);
    33. cout << "交换前,v2 容器容量:" << v2.capacity() << endl;
    34. cout << "交换前,v2 容器大小:" << v2.size() << endl;
    35. v1.swap(v2);
    36. cout << "交换后,v1 容器中的元素:";
    37. print(v1);
    38. cout << "交换后,v1 容器容量:" << v1.capacity() << ", 容器大小:" << v1.size() << endl;
    39. cout << "交换后,v2 容器中的元素:";
    40. print(v2);
    41. cout << "交换后,v2 容器容量:" << v2.capacity() << ", 容器大小:" << v2.size() << endl;
    42. //可以巧妙使用互换容器收缩内存空间,使用vector匿名对象与当前vector互换容器,
    43. //匿名对象特点是当前执行完,编译器立即回收内存空间,因此互换后之间的空间被释放了。
    44. vector<int> v3;
    45. for (int i = 0; i < 5000; i++)
    46. {
    47. v3.push_back(i);
    48. }
    49. cout << "交换前,v3 容器容量:" << v3.capacity() << ", 容器大小:" << v3.size() << endl;
    50. v3.resize(5);
    51. cout << "重置resize容器大小" << endl;
    52. cout << "重置后,v3 容器容量:" << v3.capacity() << ", 容器大小:" << v3.size() << endl;
    53. //vector(v3)为使用拷贝构造函数生成一个匿名对象,使用匿名对象调用swap函数
    54. vector<int>(v3).swap(v3);
    55. cout << "与匿名对象交换后,v3 容器容量:" << v3.capacity() << ", 容器大小:" << v3.size() << endl;
    56. system("pause");
    57. return 0;
    58. }

    输出结果

    交换前,v1 容器中的元素:0      5       10      15      20
    交换前,v1 容器容量:6, 容器大小:5
    交换前,v2 容器中的元素:5      6       7       8       9       10      11
    交换前,v2 容器容量:9
    交换前,v2 容器大小:7
    交换后,v1 容器中的元素:5      6       7       8       9       10      11
    交换后,v1 容器容量:9, 容器大小:7
    交换后,v2 容器中的元素:0      5       10      15      20
    交换后,v2 容器容量:6, 容器大小:5
    交换前,v3 容器容量:5395, 容器大小:5000
    重置resize容器大小
    重置后,v3 容器容量:5395, 容器大小:5
    与匿名对象交换后,v3 容器容量:5, 容器大小:5

    2.7、vector预留空间

    减少vector在动态扩展容量时的扩展次数,函数原型:

    • reserve(int len); //容器预留len个元素长度,预留位置不初始化,元素不可访问
    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - vector - 预留空间
    7. /*函数原型
    8. reserve(int len); //容器预留len个元素长度,预留位置不初始化,元素不可访问
    9. */
    10. vector<int> v1;
    11. int* p = NULL;
    12. int count = 0;
    13. //计算初始化5000个元素,会分配多少次内存空间
    14. for (int i = 0; i < 5000; i++)
    15. {
    16. v1.push_back(i);
    17. if (p != &v1[0])
    18. {
    19. p = &v1[0];
    20. count++;
    21. }
    22. }
    23. cout << "分配内存空间次数:" << count << endl;
    24. //预留空间
    25. vector<int> v2;
    26. v2.reserve(5000);
    27. p = NULL;
    28. count = 0;
    29. for (int i = 0; i < 5000; i++)
    30. {
    31. v2.push_back(i);
    32. if (p != &v2[0])
    33. {
    34. p = &v2[0];
    35. count++;
    36. }
    37. }
    38. cout << "预留空间后,分配内存空间次数:" << count << endl;
    39. system("pause");
    40. return 0;
    41. }

    输出结果

    分配内存空间次数:22
    预留空间后,分配内存空间次数:1

    2.8、vector存放内置数据类型

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. void print(int val)
    6. {
    7. cout << val << "\t";
    8. }
    9. int main()
    10. {
    11. // STL - vector - 存放内置数据类型
    12. //创建vetor容器对象,并且通过模板参数指定容器中存放的数据类型
    13. vector<int> v;
    14. //向容器中存放数据
    15. v.push_back(21);
    16. v.push_back(15);
    17. v.push_back(87);
    18. //v.begin()返回迭代器,这个迭代器指向容器中第一个数据
    19. //vector::iterator 拿到vector这个容器的迭代器类型
    20. vector<int>::iterator itBegin = v.begin();
    21. //v.end()返回迭代器,这个迭代器指向容器中最后一个元素的下一个位置
    22. vector<int>::iterator itEnd = v.end();
    23. cout << "--- 遍历方式一 while ---" << endl;
    24. //遍历方式一
    25. while (itBegin != itEnd)
    26. {
    27. cout << *itBegin << "\t";
    28. itBegin++;
    29. }
    30. cout << endl;
    31. cout << endl << "--- 遍历方式二 for ---" << endl;
    32. //遍历方式二
    33. for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    34. {
    35. cout << *it << "\t";
    36. }
    37. cout << endl;
    38. cout << endl << "--- 遍历方式二 for_each ---" << endl;
    39. //遍历方式三 - STL提供的遍历算法
    40. for_each(v.begin(), v.end(), print);
    41. system("pause");
    42. return 0;
    43. }

    输出结果

    --- 遍历方式一 while ---
    21      15      87

    --- 遍历方式二 for ---
    21      15      87

    --- 遍历方式二 for_each ---
    21      15      87

    2.9、vector存放自定义数据类型

    1. #include
    2. #include
    3. using namespace std;
    4. //自定义类型
    5. class Person
    6. {
    7. public:
    8. string name;
    9. int age;
    10. Person(string _name, int _age): name(_name), age(_age) {}
    11. };
    12. int main()
    13. {
    14. // STL - vector - 存放自定义数据类型
    15. Person p1("Tracy", 20);
    16. Person p2("Timo", 27);
    17. Person p3("Alice", 15);
    18. cout << "--- vector存放对象 ---" << endl;
    19. vector v1;
    20. v1.push_back(p1);
    21. v1.push_back(p2);
    22. v1.push_back(p3);
    23. //遍历
    24. for (vector::iterator it = v1.begin(); it < v1.end(); it++)
    25. {
    26. cout << "name = " << it->name << ", age = " << (*it).age << endl;
    27. }
    28. cout << endl << "--- vector存放对象指针 ---" << endl;
    29. vector v2;
    30. v2.push_back(&p1);
    31. v2.push_back(&p2);
    32. v2.push_back(&p3);
    33. //遍历
    34. for (vector::iterator it = v2.begin(); it < v2.end(); it++)
    35. {
    36. cout << "name = " << (*it)->name << ", age = " << (*it)->age << endl;
    37. }
    38. system("pause");
    39. return 0;
    40. }

    输出结果

    --- vector存放对象 ---
    name = Tracy, age = 20
    name = Timo, age = 27
    name = Alice, age = 15

    --- vector存放对象指针 ---
    name = Tracy, age = 20
    name = Timo, age = 27
    name = Alice, age = 15

    2.10、 容器嵌套容器

    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - vector - 容器嵌套容器
    7. vectorint>> v;
    8. vector<int> v1;
    9. vector<int> v2;
    10. vector<int> v3;
    11. for (int i = 0; i < 3; i++)
    12. {
    13. v1.push_back(i + 1);
    14. v2.push_back(i + 5);
    15. v3.push_back(i + 10);
    16. }
    17. v.push_back(v1);
    18. v.push_back(v2);
    19. v.push_back(v3);
    20. //遍历
    21. for (vectorint>>::iterator it = v.begin(); it < v.end(); it++)
    22. {
    23. for (vector<int>::iterator vit = (*it).begin(); vit < (*it).end(); vit++)
    24. {
    25. cout << *vit << "\t";
    26. }
    27. cout << endl;
    28. }
    29. system("pause");
    30. return 0;
    31. }

    输出结果

    1       2       3
    5       6       7
    10      11      12

    3、String容器 

    string是C++风格的字符串,本质上是一个类。

    string和char*区别:

    • char*是一个指针
    • string是一个类,类内部封装了char*,管理这个字符串,是一个char*型的容器

    string特点:

    • string类内部封装了很多成员方法,如find、copy、delete、replace、insert等。
    • string管理char*所分配的内存,不用担心复制越界和取值越界等问题,由类内部负责处理 

    3.1、string构造函数

    string构造函数原型: 

    • string();                              //创建一个空的字符 串,如 string str;
    • string(const char* s);         //使用字符串s初始化
    • string(const string& str);   //使用一个string对象初始化另一个string对象
    • string(int n, char c);          //使用n个字符c初始化
    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - string - 构造函数
    7. /*构造原型:
    8. 1、string();                    //创建一个空的字符 串,如 string str;
    9. 2、string(const char* s);       //使用字符串s初始化
    10. 3、string(const string& str);   //使用一个string对象初始化另一个string对象
    11. 4、string(int n, char c);       //使用n个字符c初始化
    12. */
    13. //1、string();             
    14. string s1;
    15. cout << "s1 = " << s1 << endl;
    16. //2、string(const char* s);   
    17. const char* c = "I am Tracy";
    18. string s2(c);
    19. cout << "s2 = " << s2 << endl;
    20. //3、string(const string& str); 
    21. string s3(s2);
    22. cout << "s3 = " << s3 << endl;
    23. //4、string(int n, char c); 
    24. string s4(5, 'k');
    25. cout << "s4 = " << s4 << endl;
    26. system("pause");
    27. return 0;
    28. }

    输出结果

    s1 =
    s2 = I am Tracy
    s3 = I am Tracy
    s4 = kkkkk 

    3.2、string赋值操作

    赋值函数原型:

    • string& operator=(const char* s);        //char*类型字符串赋值给当前字符串
    • string& operator=(const string& s);     //把字符串s赋值给当前字符串
    • string& operator=(char c);                  //字符赋值给当前字符串
    • string& assign(const char* s);            //把字符串s赋值给当前字符串
    • string& assign(const char *s, int n);   //把字符串s的前n个字符赋值给当前字符串
    • string& assign(const string& s);        //把字符串s赋值给当前字符串
    • string& assign(int n, char c);             //用n个字符c赋值给当前字符串
    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - string - 赋值操作
    7. /*赋值函数原型:
    8. 1、string& operator=(const char* s);      //char*类型字符串赋值给当前字符串
    9. 2、string& operator=(const string& s);     //把字符串s赋值给当前字符串
    10. 3、string& operator=(char c);              //字符赋值给当前字符串
    11. 4、string& assign(const char* s);          //把字符串s赋值给当前字符串
    12. 5、string& assign(const char *s, int n);   //把字符串s的前n个字符赋值给当前字符串
    13. 6、string& assign(const string& s);        //把字符串s赋值给当前字符串
    14. 7、string& assign(int n, char c);          //用n个字符c赋值给当前字符串赋值操作
    15. */
    16. //1、string& operator=(const char* s);
    17. const char* s = "Hello, I am Tray.";
    18. string s1 = s;
    19. cout << "s1 = " << s1 << endl;
    20. //2、string& operator=(const string& s);
    21. string s2 = s1;
    22. cout << "s2 = " << s2 << endl;
    23. //3、string& operator=(char c); 
    24. string s3 = "w";
    25. cout << "s3 = " << s3 << endl;
    26. //4、string& assign(const char* s);
    27. string s4;
    28. s4.assign(s);
    29. cout << "s4 = " << s4 << endl;
    30. //5、string& assign(const char *s, int n);
    31. string s5;
    32. s5.assign(s, 5);
    33. cout << "s5 = " << s5 << endl;
    34. //6、string& assign(const string& s);
    35. string s6;
    36. s6.assign(s5);
    37. cout << "s6 = " << s6 << endl;
    38. //7、string& assign(int n, char c); 
    39. string s7;
    40. s7.assign(5, 'k');
    41. cout << "s7 = " << s7 << endl;
    42. system("pause");
    43. return 0;
    44. }

    输出结果

    s1 = Hello, I am Tray.
    s2 = Hello, I am Tray.
    s3 = w
    s4 = Hello, I am Tray.
    s5 = Hello
    s6 = Hello
    s7 = kkkkk       

    3.3、string字符串拼接 

    实现字符串在结尾处拼接,字符串拼接函数原型:

    • string& operator+=(const char* str);       //重载+=操作符
    • string& operator+=(const char c);          //重载+=操作符
    • string& operator+=(const string& str);   //重载+=操作符
    • string& append(const char *s);             //把字符串s连接到当前字符串结尾
    • string& append(const char *s, int n);    //把字符串s的前n个字符连接到当前字符串结尾
    • string& append(const string &s);         //同operator+=(const string& str);
    • string& append(const string& s, int pos, int n); //字符串s中从pos开始的n个字符连接到当前字符串结尾
    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - string - 字符串拼接
    7. /*字符串拼接函数原型:
    8. 1、string& operator+=(const char* str);     //重载+=操作符
    9. 2、string& operator+=(const char c);        //重载+=操作符
    10. 3、string& operator+=(const string& str);   //重载+=操作符
    11. 4、string& append(const char *s);           //把字符串s连接到当前字符串结尾
    12. 5、string& append(const char *s, int n);    //把字符串s的前n个字符连接到当前字符串结尾
    13. 6、string& append(const string &s);         //同operator+=(const string& str);
    14. 7、string& append(const string& s, int pos, int n); //字符串s中从pos开始的n个字符连接到当前字符串结尾
    15. */
    16. const char* c = "I am busy.";
    17. //1、string& operator+=(const char* str);
    18. string s1 = "I";
    19. s1 += " am Tracy.";
    20. cout << "s1 = " << s1 << endl;
    21. //2、string& operator+=(const char c); 
    22. s1 += c;
    23. cout << "s1 = " << s1 << endl;
    24. //3、string& operator+=(const string& str);
    25. string s2 = "I am working.";
    26. s1 += s2;
    27. cout << "s1 = " << s1 << endl;
    28. //4、string& append(const char *s);   
    29. s2.append(c);
    30. cout << "s2 = " << s2 << endl;
    31. //5、string& append(const char *s, int n);   
    32. s2.append("I can finish my work.", 5);
    33. cout << "s2 = " << s2 << endl;
    34. //6、string& append(const string &s); 
    35. string s3 = "Hello,";
    36. s3.append(s2);
    37. cout << "s3 = " << s3 << endl;
    38. //7、string& append(const string& s, int pos, int n);
    39. s1.append(s3, 11,4);
    40. cout << "s1 = " << s1 << endl;
    41. system("pause");
    42. return 0;
    43. }

    输出结果

    s1 = I am Tracy.
    s1 = I am Tracy.I am busy.
    s1 = I am Tracy.I am busy.I am working.
    s2 = I am working.I am busy.
    s2 = I am working.I am busy.I can
    s3 = Hello,I am working.I am busy.I can
    s1 = I am Tracy.I am busy.I am working.work

    3.4、string查找和替换

    查找指定字符串是否存在,替换为在指定位置替换字符串,函数原型如下:

    查找(未找到返回-1):

    • int find(const string& str, int pos = 0) const;        //查找str第一次出现的位置,从pos开始查找 
    • int find(const char* s, int pos = 0) const;            //查找s第一次出现的位置,从pos开始查找
    • int find(const char* s int pos, int n) const;          //从pos位置查找 s的前n个字符第一次出现的位置
    • int find(const char c, int pos = 0) const;             //查找字符c第一次出现的位置
    • int rfind(const string& str, int pos = npos) const; //查找str最后一次出现的位置,从pos开始查找
    • int rfind(const char* s, int pos = npos) const;   //查找s最后一次出现的位置,从pos开始查找
    • int rfind(const char* s, int pos, int n) const;     //从pos查找 s的前n个字符最后一次出现的位置
    • int rfind(const char c, int pos = 0) const;         //查找字符c最后一次出现的位置

    替换:

    • string& replace(int pos, int n, const string& str);  //替换从pos开始n个字符为字符串str
    • string& replace(int pos, int n, const char* s);      //替换从pos开始的n个字符为字符串s
    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - string - 查找和替换
    7. /*函数原型:
    8. 查找:
    9. 1、int find(const string& str, int pos = 0) const;     //查找str第一次出现的位置,从pos开始查找 
    10. 2、int find(const char* s, int pos = 0) const;         //查找s第一次出现的位置,从pos开始查找
    11. 3、int find(const char* s int pos, int n) const;       //从pos位置查找 s的前n个字符第一次出现的位置
    12. 4、int find(const char c, int pos = 0) const;          //查找字符c第一次出现的位置
    13. 5、int rfind(const string& str, int pos = npos) const; //查找str最后一次出现的位置,从pos开始查找
    14. 6、int rfind(const char* s, int pos = npos) const;    //查找s最后一次出现的位置,从pos开始查找
    15. 7、int rfind(const char* s, int pos, int n) const;     //从pos查找 s的前n个字符最后一次出现的位置
    16. 8、int rfind(const char c, int pos = 0) const;         //查找字符c最后一次出现的位置
    17. 替换
    18. 9、string& replace(int pos, int n, const string& str); //替换从pos开始n个字符为字符串str
    19. 10、string& replace(int pos, int n, const char* s);    //替换从pos开始的n个字符为字符串s
    20. */
    21. string s = "I am happy,I am working now with happiness.";
    22. string sf = "ha";
    23. const char* sc = "am";
    24. //1、int find(const string & str, int pos = 0) const;
    25. cout << "1、 pos = " << s.find(sf) << endl;
    26. cout << "1、 pos = " << s.find(sf, 4) << endl;
    27. int pos = s.find("win");
    28. cout << "1、未找到时, pos = " << pos << endl;
    29. //2、int find(const char* s, int pos = 0) const; 
    30. cout << "2、 pos = " << s.find(sc) << endl;
    31. cout << "2、 pos = " << s.find(sc, 1) << endl;
    32. //3、int find(const char* s int pos, int n) const;
    33. cout << "3、 pos = " << s.find(sc, 10, 2) << endl;
    34. //4、int find(const char c, int pos = 0) const; 
    35. cout << "4、 pos = " << s.find('a') << endl;
    36. cout << "4、 pos = " << s.find('a', 10) << endl;
    37. //5、int rfind(const string & str, int pos = npos) const;
    38. cout << "5、 pos = " << s.rfind(sf) << endl;
    39. cout << "5、 pos = " << s.rfind(sf, 15) << endl;
    40. //6、int rfind(const char* s, int pos = npos) const;
    41. cout << "6、 pos = " << s.rfind(sc) << endl;
    42. cout << "6、 pos = " << s.rfind(sc, 12) << endl;
    43. //7、int rfind(const char* s, int pos, int n) const; 
    44. cout << "7、 pos = " << s.rfind(sc, 10, 2) << endl;
    45. //8、int rfind(const char c, int pos = 0) const; 
    46. cout << "8、 pos = " << s.rfind('p') << endl;
    47. cout << "8、 pos = " << s.rfind('p', 15) << endl;
    48. //9、string & replace(int pos, int n, const string & str);
    49. s.replace(5, 5, sf);
    50. cout << "9、s = " << s << endl;
    51. //10、string & replace(int pos, int n, const char* s);
    52. s.replace(5, 2, "happy");
    53. cout << "10、s = " << s << endl;
    54. system("pause");
    55. return 0;
    56. }

    输出结果

    1、 pos = 5
    1、 pos = 5
    1、未找到时, pos = -1
    2、 pos = 2
    2、 pos = 2
    3、 pos = 13
    4、 pos = 2
    4、 pos = 13
    5、 pos = 33
    5、 pos = 5
    6、 pos = 13
    6、 pos = 2
    7、 pos = 2
    8、 pos = 36
    8、 pos = 8
    9、s = I am ha,I am working now with happiness.
    10、s = I am happy,I am working now with happiness.

    3.5、string字符串比较

    字符串比较是按字符的ASCII码进行比较的,相等=返回0, 大于>返回1,小于<返回-1,函数原型如下:

    • int compare(const string& s) const;
    • int compare(const char* s) const;
    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - string - 字符串比较
    7. /*函数原型:
    8. 1、int compare(const string& s) const;
    9. 2、int compare(const char* s) const;
    10. */
    11. string s = "I am happy";
    12. string s1 = "I am happy";
    13. string s2 = "I am happy.";
    14. string s3 = "I am busy.";
    15. //1、int compare(const string& s) const;
    16. cout << "1、比较结果:" << s.compare(s1) << endl;
    17. cout << "1、比较结果:" << s.compare(s2) << endl;
    18. cout << "1、比较结果:" << s.compare(s3) << endl;
    19. //2、int compare(const char* s) const;
    20. cout << "2、比较结果:" << s.compare("I am happy") << endl;
    21. cout << "2、比较结果:" << s.compare("I am happy.") << endl;
    22. cout << "2、比较结果:" << s.compare("I am busy") << endl;
    23. system("pause");
    24. return 0;
    25. }

    输出结果

    1、比较结果:0
    1、比较结果:-1
    1、比较结果:1
    2、比较结果:0
    2、比较结果:-1
    2、比较结果:1

    3.6、字符存取 

    string中单个字符存取有两种方式:

    • char& operator[](int n); //通过[]运算符重载方式取获取字符
    • char& at(int n);             //通过at方法获取字符
    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - string - 字符存取
    7. /*函数原型:
    8. 1、char& operator[](int n); //通过[]运算符重载方式取获取字符
    9. 2、char& at(int n);         //通过at方法获取字符
    10. */
    11. cout << "---- 获取字符 ----" << endl;
    12. string s = "operator";
    13. //1、char& operator[](int n);
    14. cout << "1、获取第3个字符:" << s[2] << endl;
    15. //遍历所有字符
    16. for (int i = 0; i < s.size(); i++)
    17. {
    18. cout << s[i] << "\t";
    19. }
    20. cout << endl;
    21. //2、char& at(int n); 
    22. cout << "2、获取第3个字符:" << s.at(2) << endl;
    23. //cout << "2、获取第3个字符:" << s.at(21) << endl; //若获取越界字符,运行时将抛出异常
    24. //遍历所有字符
    25. for (int i = 0; i < s.size(); i++)
    26. {
    27. cout << s.at(i) << "\t";
    28. }
    29. cout << endl;
    30. cout << endl << "---- 修改字符 ----" << endl;
    31. s[3] = 'x';
    32. cout << "1、修改后字符串 = " << s << endl;
    33. s.at(5) = 'y';
    34. cout << "2、修改后字符串 = " << s << endl;
    35. system("pause");
    36. return 0;
    37. }

    输出结果

    ---- 获取字符 ----
    1、获取第3个字符:e
    o       p       e       r       a       t       o       r
    2、获取第3个字符:e
    o       p       e       r       a       t       o       r

    ---- 修改字符 ----
    1、修改后字符串 = opexator
    2、修改后字符串 = opexayor

    3.7、string插入和删除

    函数原型:

    插入:

    • string& insert(int pos, const char* s);       //插入字符串
    • string& insert(int pos, const string& str);  //插入字符串
    • string& insert(int pos, int n, char c);        //在指定位置插入n个字符c

    删除:

    • string& erase(int pos, int n= npos);         //删除从pos开始的n个字符

     

    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - string - 插入和删除
    7. /*函数原型:
    8. 插入:
    9. 1、string& insert(int pos, const char* s);       //插入字符串
    10. 2、string& insert(int pos, const string& str);  //插入字符串
    11. 3、string& insert(int pos, int n, char c);      //在指定位置插入n个字符c
    12. 删除:
    13. 4、string& erase(int pos, int n= npos);         //删除从pos开始的n个字符
    14. */
    15. string s = "happy";
    16. string si = " too.";
    17. //1、string& insert(int pos, const char* s);
    18. s.insert(0, " am ");
    19. cout << "1、s = " << s << endl;
    20. //2、string& insert(int pos, const string& str);
    21. s.insert(9, si);
    22. cout << "2、s = " << s << endl;
    23. //3、string& insert(int pos, int n, char c); 
    24. s.insert(0, 3, 'I');
    25. cout << "3、s = " << s << endl;
    26. //4、string& erase(int pos, int n= npos); 
    27. s.erase(0, 2);
    28. cout << "4、s = " << s << endl;
    29. system("pause");
    30. return 0;
    31. }

    输出结果

    1、s =  am happy
    2、s =  am happy too.
    3、s = III am happy too.
    4、s = I am happy too. 

    3.8、string子串获取

    从字符串中获取想要的子串,函数原型:

    • string substr(int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串
    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. // STL - string - 子串获取
    7. /*函数原型:
    8. string substr(int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串
    9. */
    10. string s = "happy2022@gmail.com";
    11. int pos = s.find("@");
    12. cout << s.substr(0, pos) << endl;
    13. system("pause");
    14. return 0;
    15. }

    输出结果

    happy2022

  • 相关阅读:
    10款功能强大的网络嗅探工具应用分析
    Ubuntu安装Redis
    [附源码]java毕业设计家政管理系统
    认识一下什么是JSP
    Java 内置包装类——System类详解
    Web前端:程序员的最佳React开发工具
    【二】2D测量 Metrology——get_metrology_object_result_contour()算子
    删除 word 中嵌入文字下方的图片
    phantomjs-prebuilt: Running install script, failed in 32s
    痞子衡嵌入式:主流QuadSPI NOR Flash厂商关于QE位与IO功能复用关联设计
  • 原文地址:https://blog.csdn.net/ling1998/article/details/126081237