STL提供了三个最基本的容器:vector,list,deque
来源:互联网 发布:淘宝网羊毛衫 编辑:程序博客网 时间:2024/05/22 10:51
vector和built-in数组类似,它拥有一段连续的内存空间,并且起始地址不变,因此它能非常好的支持随机存取,即[]操作符,但由于它的内存空间是连续的,所以在中间进行插入和删除会造成内存块的拷贝,另外,当该数组后的内存空间不够时,需要重新申请一块足够大的内存并进行内存的拷贝。这些都大大影响了vector的效率。
list就是数据结构中的双向链表(根据sgi stl源代码),因此它的内存空间可以是不连续的,通过指针来进行数据的访问,这个特点使得它的随机存取变的非常没有效率,因此它没有提供[]操作符的重载。但由于链表的特点,它可以以很好的效率支持任意地方的删除和插入。
deque是一个double-ended queue,它的具体实现不太清楚,但知道它具有以下两个特点:它支持[]操作符,也就是支持随即存取,并且和vector的效率相差无几,它支持在两端的操作:push_back、push_front、pop_back、pop_front等,并且在两端操作上与list的效率也差不多。
因此在实际使用时,如何选择这三个容器中哪一个,应根据你的需要而定,一般应遵循下面的原则:
1、如果你需要高效的随即存取,而不在乎插入和删除的效率,使用vector
2、如果你需要大量的插入和删除,而不关心随即存取,则应使用list
3、如果你需要随即存取,而且关心两端数据的插入和删除,则应使用deque。
下面为msdn帮助文档中自带的一个例子,该例展示了如何使用迭代器读取列表中的元素和进行插入操作。
#include <list> #include <iostream> using namespace std ; typedef list<int> LISTINT; void main() { int rgTest1[] = {5,6,7}; int rgTest2[] = {10,11,12}; LISTINT listInt; LISTINT listAnother; LISTINT::iterator i; // Insert one at a time listInt.insert (listInt.begin(), 2); listInt.insert (listInt.begin(), 1); listInt.insert (listInt.end(), 3); // 1 2 3 for (i = listInt.begin(); i != listInt.end(); ++i) cout << *i << " "; cout << endl; // Insert 3 fours listInt.insert (listInt.end(), 3, 4); // 1 2 3 4 4 4 for (i = listInt.begin(); i != listInt.end(); ++i) cout << *i << " "; cout << endl; // Insert an array in there listInt.insert (listInt.end(), rgTest1, rgTest1 + 3); // 1 2 3 4 4 4 5 6 7 for (i = listInt.begin(); i != listInt.end(); ++i) cout << *i << " "; cout << endl; // Insert another LISTINT listAnother.insert (listAnother.begin(), rgTest2, rgTest2+3); listInt.insert (listInt.end(), listAnother.begin(), listAnother.end()); // 1 2 3 4 4 4 5 6 7 10 11 12 for (i = listInt.begin(); i != listInt.end(); ++i) cout << *i << " "; cout << endl; }
Program Output is:
1 2 3
1 2 3 4 4 4
1 2 3 4 4 4 5 6 7
1 2 3 4 4 4 5 6 7 10 11 12
- STL提供了三个最基本的容器:vector,list,deque。
- stl提供了三个最基本的容器:vector,list,deque
- STL提供了三个最基本的容器:vector,list,deque
- STL提供了三个最基本的容器:vector,list,deque。
- STL提供了三个最基本的容器:vector,list,deque
- STL提供了三个最基本的容器:vector,list,deque
- STL提供了三个最基本的容器:vector,list,deque
- STL提供了三个最基本的容器:vector、list和deque
- stl提供了三个最基本的容器:vector,list,deque
- STL提供了三个最基本的容器:vector,list,deque
- STL的三个基本容器 vector list deque
- stl提供了三个最基本的容器
- C++ STL 提供了3个序列容器 :vector, deque, list
- C++ STL基本容器string,vector,list,deque,map..[转]
- STL基本容器: string、vector、list、deque、set、map
- STL基本容器: string、vector、list、deque、set、map
- STL 基本容器 : string、vector、list、deque、set、map 的区别
- STL中基本容器string,vector,list,deque,set,map之间的区别
- Delphi Open Tools API概述
- tsung--开源多协议分布式压力测试工具
- 冒泡算法简单例子_Java
- GUI
- sqlservice 取得 6 到10 行数据
- STL提供了三个最基本的容器:vector,list,deque
- WIN32程序IP Control实现禁止输入非法字符
- PDF文件简介及PDF文档加密方法
- Linux 动态/静态库
- HttpInvoker支持不需要证书的HTTPS
- android开源项目
- 好用网站集合
- Java中的流程控制语言
- dotConnect for Oracle中关于SQL*Plus用户的OracleScript提示