经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
一篇文章彻底搞懂C++常见容器
来源:jb51  时间:2023/2/15 9:19:22  对本文有异议

1.概述

C++容器属于STL(标准模板库)中的一部分(六大组件之一),从字面意思理解,生活中的容器用来存放(容纳)水或者食物,东西,而C++中的容器用来存放各种各样的数据,不同的容器具有不同的特性,下图(思维导图)中列举除了常见的几种C++容器,而这部分C++的容器与python中的序列有很多相似之处,也许这也很好地印证了江湖上“C生万物”的说法。因本人是学完python后才学C++的,突然有种:“山重水复疑无路,柳暗花明又一村”的感觉。因为python是偏向于顶层的语言,那时候什么迭代器生成器之类的东西都不是非常清楚,然后在C++中又遇到了类似内容,便有了更好的理解,也许这就是很多人不建议初学者学习python的原因吧。

2.容器详解

2.1vector(向量)

从这个命名就可以很好地理解,在线性代数中,向量是一维的结构,而在容器中,向量也是看似一维的存储形式。可以理解为长度可变的数组。只不过在尾部增删数据的时候效率最高,其他位置增删数据则效率较低。举个例子(开胃菜):

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. // 程序的主函数
  5. int main()
  6. {
  7. vector<int> V;
  8. V.push_back(1);
  9. V.push_back(2);
  10. V.push_back(1);
  11. V.push_back(2);
  12. cout << V[0] << endl;
  13. system("pause");
  14. return 0;
  15. }

打印输出:1

从上面的例子可以看出,向量和数组的用法极其类似。当然,容器还有一个极其好用的功能,就是容器的嵌套使用。

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. // 程序的主函数
  5. int main()
  6. {
  7. vector<vector<int>> V;
  8. vector<int> sub_V;
  9. sub_V.push_back(1);
  10. sub_V.push_back(2);
  11. sub_V.push_back(1);
  12. V.push_back(sub_V);
  13. cout << V[0][1] << endl;
  14. system("pause");
  15. return 0;
  16. }

打印输出2这个时候的向量可以看作是一个二维数组,当然比二维数组更加灵活、强大。

当然向量容器还有其他更加丰富的操作。比如:

  1. int size = vec1.size(); //元素个数
  2. bool isEmpty = vec1.empty(); //判断是否为空
  3. vec1.insert(vec1.end(),5,3); //从vec1.back位置插入5个值为3的元素
  4. vec1.pop_back(); //删除末尾元素
  5. vec1.erase(vec1.begin(),vec1.end());//删除之间的元素,其他元素前移
  6. cout<<(vec1==vec2)?true:false; //判断是否相等==、!=、>=、<=...
  7. vector<int>::iterator iter = vec1.begin(); //获取迭代器首地址
  8. vector<int>::const_iterator c_iter = vec1.begin(); //获取const类型迭代器
  9. vec1.clear(); //清空元素

举个最常见的例子:

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. // 程序的主函数
  5. int main()
  6. {
  7. vector<int> V;
  8. V.push_back(1);
  9. V.push_back(2);
  10. V.push_back(3);
  11. for (vector<int>::iterator it = V.begin(); it != V.end(); it++)
  12. cout << *it << " ";
  13. cout << endl;
  14. cout << "==========================" << endl;
  15. V.insert(V.begin() + 2,10);
  16. for (vector<int>::iterator it = V.begin(); it != V.end(); it++)
  17. cout << *it << " ";
  18. system("pause");
  19. return 0;
  20. }

注意如果不是在其尾部插入数据,要传入插入位置的迭代器。

打印输出:

2.2deque(双端队列)

deque,顾名思义,从前后两端都可以进行数据的插入和删除操作,同时支持数据的快速随机访问。举个例子:

  1. #include <iostream>
  2. #include <deque>
  3. using namespace std;
  4. // 程序的主函数
  5. int main()
  6. {
  7. deque<int> D;
  8. D.push_back(1);
  9. D.push_back(2);
  10. D.push_back(3);
  11. for (deque<int>::iterator it = D.begin(); it != D.end(); it++)
  12. cout << *it << " ";
  13. cout << endl;
  14. cout << "============在其索引2的位置插入10:" << endl;
  15. D.insert(D.begin() + 2,10);
  16. for (deque<int>::iterator it = D.begin(); it != D.end(); it++)
  17. cout << *it << " ";
  18. cout << endl;
  19. cout << "============在其头部插入0:" << endl;
  20. D.push_front(0);
  21. for (deque<int>::iterator it = D.begin(); it != D.end(); it++)
  22. cout << *it << " ";
  23. cout << endl;
  24. cout << "============在其头部弹出0:" << endl;
  25. D.pop_front();
  26. for (deque<int>::iterator it = D.begin(); it != D.end(); it++)
  27. cout << *it << " ";
  28. system("pause");
  29. return 0;
  30. }

打印输出:

2.3list(列表)

列表是用双向链表实现的,所谓的双向链表,指的是既可以从链表的头部开始搜索找到链表的尾部,也可以进行反向搜索,从尾部到头部。这使得list在任何位置插入和删除元素都变得非常高效,但是随机访问速度变得非常慢,因为保存的地址是不连续的,所以list没有重载[]运算符,也就是说,访问list元素的时候,再也不像向量和双端队列那么方便,不可以像我们以前在C语言的时候,访问数组那样对其元素进行访问。
一起来看个例子:

  1. #include <iostream>
  2. #include <list>
  3. using namespace std;
  4. // 程序的主函数
  5. int main()
  6. {
  7. //list的创建和初始化
  8. list<int> lst1; //创建空list
  9.  
  10. list<int> lst2(3); //创建含有三个元素的list
  11.  
  12. list<int> lst3(3, 2); //创建含有三个元素的值为2的list
  13.  
  14. list<int> lst4(lst3); //使用lst3初始化lst4
  15.  
  16. list<int> lst5(lst3.begin(), lst3.end()); //同lst4
  17. cout << "lst4中的元素有:" << endl;
  18. for (list<int>::iterator it = lst4.begin(); it != lst4.end(); it++)
  19. cout << *it << " ";
  20. cout << endl;
  21. cout << "lst5中的元素有:" << endl;
  22. for (list<int>::iterator it = lst5.begin(); it != lst5.end(); it++)
  23. cout << *it << " ";
  24. cout << endl;
  25. system("pause");
  26. return 0;
  27. }

运行,打印输出:

然后再来看一个元素的添加,排序的例子。

  1. #include <iostream>
  2. #include <list>
  3. #include <vector>
  4. using namespace std;
  5. // 程序的主函数
  6. int main()
  7. {
  8. //list的创建和初始化
  9. list<int> lst1; //创建空list
  10.  
  11. for(int i = 0; i < 10; i++)
  12. lst1.push_back(9-i); //添加值
  13. cout << "lst1中的元素有:" << endl;
  14. for (list<int>::iterator it = lst1.begin(); it != lst1.end(); it++)
  15. cout << *it << " ";
  16. cout << endl;
  17. cout << "对lst1中的元素进行排序:" << endl;
  18. lst1.sort();
  19. for (list<int>::iterator it = lst1.begin(); it != lst1.end(); it++)
  20. cout << *it << " ";
  21. cout << endl;
  22. cout << "在索引为5的地方插入999:" << endl;
  23. list<int>::iterator insert_it = lst1.begin();
  24. for (int i = 0; i < 5; i++)
  25. insert_it++;
  26. lst1.insert(insert_it, 3, 999);
  27. for (list<int>::iterator it = lst1.begin(); it != lst1.end(); it++)
  28. cout << *it << " ";
  29. cout << endl;
  30. cout << "删除相邻重复元素后:" << endl;
  31. lst1.unique(); //删除相邻重复元素
  32. for (list<int>::iterator it = lst1.begin(); it != lst1.end(); it++)
  33. cout << *it << " ";
  34. cout << endl;
  35. system("pause");
  36. return 0;
  37. }

运行后,打印输出:

特别注意,由于list的底层是双向链表,因此insert操作无法直接像向量和双端队列一样直接插入数据,只能通过迭代器的自加移动到相应位置,再插入数据。

2.4 array(数组)

array和C语言中的数组没有太大的区别,建立后只能存储一种类型的数据,且不能改变大小。比较简单,举个例子:

  1. #include <iostream>
  2. #include <string>
  3. #include <array>
  4. using namespace std;
  5. // 程序的主函数
  6. int main()
  7. {
  8. array<int, 4> arr = {1, 3, 2};
  9. cout << "arr values:" << std::endl;
  10. for (array<int, 4>::iterator it = arr.begin(); it != arr.end(); it++) {
  11. cout << *it << " ";
  12. }
  13. cout << endl;
  14. cout << "sizeof(arr) = " << sizeof(arr) << endl;
  15. cout << "size of arr = " << arr.size() << endl;
  16. cout << "max size arr = " << arr.max_size() << endl;
  17. cout << "empty = " << (arr.empty() ? "no" : "yes") << endl;
  18. system("pause");
  19. return 0;
  20. }

当然,最常见的,array也支持嵌套,可以采用这样的方式来构建二维(多维)数组,由于比较简单,就不举例了。

2.5 string(字符串)

与vector相似的容器。专门用于保存字符。随机访问快。尾部插入删除快。在部分说法中,string不算是STL容器,但是为了内容的完整性,我们还是将其一并学习。

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. // 程序的主函数
  5. int main()
  6. {
  7. string s1 = "Bob:";
  8. string s2("hellow world!");
  9. for (int i = 0; i < s1.size(); i++)
  10. {
  11. cout << s1[i];
  12. }
  13. cout << endl;
  14. for (int i = 0; i < s2.size(); i++)
  15. {
  16. cout << s2[i];
  17. }
  18. cout << endl;
  19.  
  20. cout << s1 + s2 << endl;
  21. s1.insert(s1.size(),"you say ");
  22. cout << s1 + s2 << endl;
  23. system("pause");
  24. return 0;
  25. }

运行,打印输出如下:

通过以上例子可以发现,与我们在C语言中学习的string并没有多少区别,其实本身区别也不是很大,只是在创建了之后还可以添加元素(盲猜是新创建了一个同名的string,仅此而已),且添加元素的方式也很简单,直接通过insert(插入位置,需要添加的字符串)这样的格式添加即可。上面一个例子是从末尾添加的,所以索引肯定是s1.size()。当然还有字符串的相加,字符串的比较等,都是属于更为基础的内容,没有添加到例子当中去,感兴趣的同学可以自己找资料去学习。

2.6 map(映射)

map容器和python中的字典非常类似,或者说一模一样。都是通过键值对的方式来存储和访问数据的,底层是通过红黑树来实现的。先来看个map的创建以及初始化的例子。

  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. using namespace std;
  5. // 程序的主函数
  6. int main()
  7. {
  8. //map的创建和初始化
  9. //第一种:用insert函数插入pair数据:
  10. map<int, string> my_map;
  11. my_map.insert(pair<int, string>(1, "first"));
  12. my_map.insert(pair<int, string>(2, "second"));
  13. //第二种:用insert函数插入value_type数据:
  14. my_map.insert(map<int, string>::value_type(3, "first"));
  15. my_map.insert(map<int, string>::value_type(4, "second"));
  16. //第三种:用数组的方式直接赋值:
  17. my_map[5] = "first";
  18. my_map[6] = "second";
  19. map<int, string>::iterator it; //迭代器遍历
  20. for (it = my_map.begin(); it != my_map.end(); it++)
  21. cout << it->first << "->" <<it->second << endl;
  22. system("pause");
  23. return 0;
  24. }

运行,打印输出如下结果:

从以上结果可以看出,其中数组直接赋值的方法最简单直接,最容易理解。当然map保存的是键值对,所以前面的int类型数据(key)并不代表其位置。比方说,我们将其中的int修改为float也是可以的。代码如下:

  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. using namespace std;
  5. // 程序的主函数
  6. int main()
  7. {
  8. //map的创建和初始化
  9. //第一种:用insert函数插入pair数据:
  10. map<float, string> my_map;
  11. my_map.insert(pair<float, string>(1, "first"));
  12. my_map.insert(pair<float, string>(2, "second"));
  13. //第二种:用insert函数插入value_type数据:
  14. my_map.insert(map<float, string>::value_type(3, "first"));
  15. my_map.insert(map<float, string>::value_type(4, "second"));
  16. //第三种:用数组的方式直接赋值:
  17. my_map[5.3] = "first";
  18. my_map[6.6] = "second";
  19. map<float, string>::iterator it; //迭代器遍历
  20. for (it = my_map.begin(); it != my_map.end(); it++)
  21. cout << it->first << "->" <<it->second << endl;
  22. system("pause");
  23. return 0;
  24. }

当然,同其他的容器类型一样,map同样支持嵌套,比如:

  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. using namespace std;
  5. // 程序的主函数
  6. int main()
  7. {
  8. //map的嵌套用法
  9. map<int,map<int,string>> my_map;
  10. my_map[1][1] = "张三";
  11. my_map[1][2] = "李四";
  12. my_map[1][3] = "王五";
  13.  
  14. for (map<int, map<int, string>>::iterator it = my_map.begin(); it != my_map.end(); it++)
  15. {
  16. for (map<int, string>::iterator in_it = it->second.begin(); in_it != it->second.end(); in_it++)
  17. {
  18. cout << it->first << "年级" << in_it->first << "号同学:" << in_it->second << endl;
  19. }
  20. }
  21. cout << endl;
  22. system("pause");
  23. return 0;
  24. }

运行,打印输出如下:

还有一个很重要的问题,就是map元素的删除。map元素的删除有好多种方法,下面仅仅列举 常见几种。

  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. using namespace std;
  5.  
  6. void printMap(const map<string, int>& students)
  7. {
  8. for (auto ii = students.begin(); ii != students.end(); ii++)
  9. {
  10. cout << "姓名:" << ii->first
  11. << " \t诗作: " << ii->second << "篇"
  12. << endl;
  13. }
  14. cout << endl;
  15. }
  16.  
  17. int main(int argc, char* argv[]) {
  18. map<string, int> students;
  19. students["李白"] = 346;
  20. students["杜甫"] = 300;
  21. students["王维"] = 200;
  22. students["李商隐"] = 113;
  23. students["杜牧"] = 156;
  24. cout << "原map:" << endl;
  25. printMap(students);
  26.  
  27. students.erase("李白");
  28. cout << "删除 李白 后:" << endl;
  29. printMap(students);
  30.  
  31. students.erase(std::begin(students));
  32. cout << "删除第一个元素后:" << endl;
  33. printMap(students);
  34.  
  35. map<string, int>::iterator iter = students.find("杜牧");
  36. students.erase(iter);
  37. cout << "删除杜牧后:" << endl;
  38. printMap(students);
  39. system("pause");
  40. return 0;
  41. }

运行后,打印输出:

从上面的例子也可以看出,map中的键值对不一定是按照我们创建的顺序保存数据,map会按照key的值内部进行排序,但是保持其键值对的对应关系不变。

2.7 set(集合)

set也是一种关联性容器,它同map一样,底层使用红黑树实现,插入删除操作时仅仅移动指针即可,不涉及内存的移动和拷贝,所以效率比较高。从中文名就可以明显地看出,在set中不会存在重复的元素,若是保存相同的元素,将直接视为无效,我们先来看个简单的例子(关于set的创建和元素的添加等):

  1. #include <iostream>
  2. #include <set>
  3. #include <vector>
  4. using namespace std;
  5. // 程序的主函数
  6. int main()
  7. {
  8. vector<int> ivec;
  9. for (vector<int>::size_type i = 0; i != 10; i++) {
  10. ivec.push_back(i);
  11. ivec.push_back(i);
  12. }
  13. set<int> iset(ivec.begin(), ivec.end());
  14. cout << "向量中的元素为:" << endl;
  15. for (vector<int>::iterator it = ivec.begin(); it != ivec.end(); it++)
  16. {
  17. cout << *it << " ";
  18. }
  19. cout << endl;
  20. cout << "集合中的元素为:" << endl;
  21. for (set<int>::iterator it = iset.begin(); it != iset.end(); it++)
  22. {
  23. cout << *it << " ";
  24. }
  25. cout << endl;
  26. cout << "向量的大小为:" << endl;
  27. cout << ivec.size() << endl;
  28. cout << "集合的大小为:" << endl;
  29. cout << iset.size() << endl;
  30.  
  31. system("pause");
  32. return 0;
  33. }

打印输出:

上面例子的方法,相当于直接将向量的值赋给了集合,从而顺便创建了集合,那么如果想通过逐一赋值的方式创建集合,又该如何编写代码呢?如何清除集合中的元素呢?以及是否知道某元素在集合中呢?同样我们通过一段代码来看一下。

  1. #include <iostream>
  2. #include <set>
  3. #include <vector>
  4. #include <string>
  5. using namespace std;
  6. // 程序的主函数
  7. int main()
  8. {
  9. set<string> set1;
  10. set1.insert("the");
  11.  
  12. //删除集合
  13. while (!set1.empty())
  14. {
  15. //获取头部
  16. set<string>::iterator it = set1.begin();
  17. //打印头部元素
  18. cout << *it << endl;
  19.  
  20. //从头部删除元素
  21. set1.erase(set1.begin());
  22. }
  23. set<int>set2;
  24. for (int i = 100; i < 110; i++)
  25. set2.insert(i);
  26. cout << "set2中5出现的次数为:";
  27. cout << set2.count(5) << endl;
  28. set2.clear();
  29. cout << "set2清除之后的大小为:";
  30. cout << set2.size() << endl;
  31. system("pause");
  32. return 0;
  33. }

运行,打印输出:

通过以上的例子可以发现,set可以直接通过insert()方法添加数据,而数据内部是自动排序的,所以不用担心数据的顺序问题,当然也可以像map那样,通过迭代器添加到指定位置,查询set中有无该数据可以直接使用count()方法,有则返回1,无则返回0

3.后记

到此这篇关于彻底搞懂C++常见容器的文章就介绍到这了,更多相关C++常见容器内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号