您的位置:首页 > 产品设计 > UI/UE

STL提供了三个最基本的容器:vector,list,deque

2013-04-28 15:56 423 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: