STL之如何选择顺序容器

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
简介: 一、顺序容器的分类   顺序容器:vector向量、list链表、deque双端队列;   优先级最高的是vector向量,它的速度比较快,优点最多;   在程序设计中,容器可以切换; 1 #include 2 #include 3 #include 4 #inclu...

一、顺序容器的分类

  顺序容器:vector向量、list链表、deque双端队列;

  优先级最高的是vector向量,它的速度比较快,优点最多;

  在程序设计中,容器可以切换;

 1 #include <iostream>
 2 #include <vector>
 3 #include <list>
 4 #include <deque>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     vector<int> Ivec;
11     list<int>  Ilist;   //利用链表
12     deque<int> Ideque;
13 
14     Ivec.push_back(10);
15     Ivec.push_back(20);
16     Ivec.push_back(30);
17     Ivec.push_back(30);
18     Ivec.push_back(30);
19     Ivec.push_back(30);
20     Ivec.push_back(30);
21     vector<int>::iterator it=Ivec.begin();
22     it++;
23     it++;
24     Ivec.insert(it, 59);    //插入操作比较慢,因为插入点之后的数据都需要向后移动
25     it++;
26     Ivec.erase(it);         //删除操作也比较慢,数组中删除同样需要移动数据
27 
28     sort(Ivec.begin(), v.end());    //速度比较快,sort中利用下标快速排序,
29     //存在下标,在排好序的情况下,利用二分法查找很快;
30     if(binary_search(Ivec.begin(), Ivec.end(), 59)){
31         std::cout << "find 59 ok" << std::endl;    
32     }else{
33         std::cout << "find 59 error" << std::endl;
34 
35     sort(Ivec.begin(), v.end());    //速度比较快,sort中利用下标快速排序,
36     //存在下标,在排好序的情况下,利用二分法查找很快;
37     if(binary_search(Ivec.begin(), Ivec.end(), 59)){
38         std::cout << "find 59 ok" << std::endl;
39     }else{
40         std::cout << "find 59 error" << std::endl;
41     }
42 
43     Ilist.push_back(10);
44     Ilist.push_back(20);
45     Ilist.push_back(30);
46     Ilist.push_back(30);
47     Ilist.push_back(30);
48     Ilist.push_back(30);
49     list<int>::iterator it2=Ilist.begin();
50     it2++;
51     it2++;
52     Ilist.insert(it2, 59);  //插入操作比较快,因为链表的插入不需要移动数据
53     it2++;
54     Ilist.erase(it2);       //在链表中直接操作指针即可
55 
56     Ilist.sort();           //链表中排序比较慢
57     //二分法查找,在list是伪二分法查找,速度比较慢
58     if(binary_search(Ilist.begin(), Ilist.end(), 59)){
59            std::cout << "find 59 ok" << std::endl;
60     }else{
61         std::cout << "find 59 error" << std::endl;
62     }
63 
64     //deque,可以在前端操作,操作灵活,所有的操作比vector慢一点点,分区存储,可以保存大量数据
65     Ideque.push_back(50);
66     Ideque.push_front(10);
67 
68     return 0;
69 }

 

相关文章
|
3月前
|
存储 算法 C++
STL几个容器的比较
STL几个容器的比较
|
4月前
|
存储 C++ 容器
【C++】STL容器——vector类的使用指南(含代码演示)(11)
【C++】STL容器——vector类的使用指南(含代码演示)(11)
|
4月前
|
设计模式 C++ iOS开发
【C++】STL容器适配器入门:【堆】【栈】【队列】(16)
【C++】STL容器适配器入门:【堆】【栈】【队列】(16)
【C++】STL容器适配器入门:【堆】【栈】【队列】(16)
|
1月前
|
存储 安全 C++
深入理解C++ STL中的vector容器
深入理解C++ STL中的vector容器
12 0
|
2月前
|
存储 算法 C++
万字长文:C++模板与STL【常用STL容器】
万字长文:C++模板与STL【常用STL容器】
|
2月前
|
存储 算法 C++
C++ STL精通之旅:向量、集合与映射等容器详解
C++ STL精通之旅:向量、集合与映射等容器详解
102 0
|
2月前
|
存储 前端开发 C++
【C++入门到精通】C++入门 —— 容器适配器、stack和queue(STL)
在C++中​​std::stack​​​是一个模板类,它是基于容器的适配器,用于实现堆栈数据结构。堆栈是一种后进先出(LIFO)的数据结构,类似于现实生活中的一叠盘子。
27 4
|
2月前
|
存储 定位技术 C++
C++ STL容器与常用库函数
C++ STL容器与常用库函数
72 0
C++ STL容器与常用库函数
|
3月前
|
存储 C++ 容器
|
3月前
|
C++ 容器
stl容器笔记
stl容器笔记