C + + Three containers: The difference between list, vector and deque

Source: Internet
Author: User

In the writing of C + + program will find that STL is a good thing, reduce the amount of code, so that the code reuse rate greatly improved, reduce the burden of the program ape. There is a container, you will find that if you write a list, queue, or an array, you have to take the time to worry about how to maintain, the inside of the pointer Ah, memory enough to use Ah, length problems, there is no possibility of overflow ah and so on a series of problems waiting for us to solve, or more headache. So the appearance of the container solves this problem, it will be the data structure is encapsulated into a class, only need to add a header file, we can easily apply, not so complicated, even the pointer is encapsulated into an iterator, it is more convenient, more humane, convenient for our programming, It's a great boon for programmers!!

The container classes in C + + include "Sequential storage Structure" and "associative storage Structure", which includes vector,list,deque and so on, while the latter includes Set,map,multiset,multimap and so on. If you need to store the number of elements between the compiler can be determined, you can use the array to store, otherwise, you need to use the container class.

1. Vector
Continuous Storage structure, each element is contiguous in memory;efficient random access and insert/delete operations at the end, but the insertion/deletion operation in other locations is inefficient;is equivalent to an array, but differs from an array: the expansion of the memory space。 Vector support does not specify a vector-sized store, but the expansion of the array requires the programmer to write it himself.
Vector's memory allocation implementation principle:
When STL is implemented internally, first allocates a very large amount of memory space to prepare for storage, that is, the size returned by the capacity () function, when the allocated space is exceeded, and then the whole memory storage (VS6.0 is twice times, VS2005 is 1.5 times times), soThis gives the sense that a vector can not specify the size of a vector that is a continuous memory。 Typically, this default memory allocation can do most of the storage.
Expansion space (no matter how large) should be done:
(1) Configure a new space
(2) Move old element one by one to new site
(3) Release the original space back to the system
Note: Vector data is arranged and manipulated in a very similar way to array. The only difference between the two is the flexibility of space utilization. The expansion space of the Array should be written by the programmer himself.
The vector class defines several constructors for defining and initializing vector objects:
Vector<t> v1; The vector holds an object of type T. The default constructor v1 is empty.
Vector<t> v2 (v1); V2 is a copy of v1.
Vector<t> v3 (n, i); The v3 contains n elements with a value of I.
Vector<t> v4 (n); V4 contains n copies of elements that are initialized with values.
2, Deque
Continuous Storage structureThat each of its elements is contiguous in memory, similar to a vector, except thatDeque provides a level two array structure, the first level is exactly like a vector, represents the actual container, and the other level maintains the first address of the container. In this way, deque, in addition to having all the functions of a vector,also supports efficient first/end insert/delete operations.
Deque dual-ended queue Double-end
Deque is a functionally integrated vector and list.
Advantages:(1) Convenient random access, that is, support [] operator and vector.at ()
(2) Easy to insert and delete inside
(3) Push, pop on both ends
Disadvantages:Memory-intensive
Usage Differences:
(1) If you need efficient immediate access, instead of the efficiency of INSERT and delete, use vector
(2) If you need a large number of insertions and deletions and do not care about random access, you should use the list
(3) If you need random access, and care about the insertion and deletion of both ends of the data, you should use Deque
3. List
non-contiguous storage structure, has a doubly linked list structure, each element maintains a pair of forward and back pointers, and therefore supports forward/back traversal.supports efficient random insert/delete operations, but is inefficient for random access, and because additional maintenance pointers are required, and it's a lot more expensive.。 Each node includes a message fast info, a precursor pointer pre, and a rear-drive pointer post. You can easily add and delete operations without allocating the necessary memory size. Use a non-contiguous memory space for storage.
Advantages:(1) Do not use continuous memory to complete dynamic operation.
(2) Easy to insert and delete inside
(3) Push, pop on both ends
Disadvantages:(1) No internal random access, i.e. [] operator and vector.at () are not supported
(2) memory-intensive relative to Verctor
Usage Differences:
(1) If you need efficient immediate access, instead of the efficiency of INSERT and delete, use vector
(2) If you need a large number of insertions and deletions and do not care about random access, you should use the list
(3) If you need random access, and care about the insertion and deletion of both ends of the data, you should use Deque
4, vector vs. list vs. Deque:
A, if you need random access operation, select vector;
b, if you already know the number of elements to be stored, select vector;
C, if you need to insert/delete randomly (not just at both ends), select the list
D, only need to be in the first end of the insertion/deletion operation, but also to take into account the efficiency of random access, only select Deque, otherwise all select vector.
E, if the need for random insertion/deletion, but also need random access, you need to make a compromise between the vector and list-deque.
F, when you want to store a large responsible class object, the list is better than the vector, of course, you can also use vectors to store pointers to objects,
It is also highly efficient, but the maintenance of pointers is very error-prone and therefore not recommended.

question one: The difference between list and vector:
(1) Vector allocates a contiguous address space for the stored object, the efficiency of random access is very high。 Butinserts and deletes need to move a lot of data, less efficient。 Especially when vectors are stored
object is large, or the constructor is complex, the copy constructor is executed when the existing element is copied.
(2) The objects in the list are discrete, and random accesses need to traverse the whole list,access efficiency is lower than vector。 But inserting elements into the list, especially at the end of theInsert, high efficiency, you only need to change the pointer of the element.

(3) vector is unidirectional, and list is bidirectional ;

(4) The iterator in the vector is released after use, but the list of the linked list is different, and its iterator can continue to use after it is used; the list is unique;

principle of Use:
(1) Using vectors if efficient random access is required, rather than the efficiency of insertion and deletion;
(2) If you need a lot of efficient delete insert, but do not care about the access time, then use list;
(3) If the need for funny random access, but also a large number of end-to-end insertion and deletion is recommended to use Deque, which is a compromise between list and vector;
question two: constant container const
Const vector<int> VEC (10);//In this containercapacity and size and valuesCan never be changed,the const modifier is vector.;
Iterator: const vector<int>::const_iterrator ite; Constant iterator;
Note: The const vector <int> VEC (10)--With the const int A[10] is one thing, meaning that VEC has only 10 elements that cannot be added, and the elements inside cannot be changed .
Vector<int> A (ten); const vector<int> B () a[1]=10;//correct b[1]=10;//error a.resize (20);//correct b.resize (20);//Error
Vector <const int> VEC (ten);  There is no such usage at the moment, so it is used as a vector <int>vec, and for Vector<const int>, there is no such usage under GCC, but in VS2008 it is used as a vector< Int> this type to deal with;
question three: capacity V.s size
A, capacity is the total number of elements that can be filled before the container needs to grow;only containers with continuous storage have the concept of capacity.(e.g. vector,deque,string), list does not need to be capacity.
b, size is the number of elements currently stored by the container.
c, vector default capacity initial value, and growth rules are dependent on the compiler.
question four: When storing a custom class object with vectors, the custom class object must satisfy:
A, there is a parameterless constructor available for invocation (default or custom);

b, there are available copy assignment functions (default or Custom)

question five: iterator iterator    

A, vector, and deque iterators support arithmetic operations, and the list's iterators can only perform ++/--operations and do not support ordinary arithmetic operations.

B. The iterator in the vector is released after use, but the list of lists is different, and its iterators can continue to be used after use; the list is unique;

     Ite=find (Vec.begin (), Vec.end (), ();     Vec.insert (ite,2,77);  Insert data before the position of the iterator tag;     cout<<*ite<<endl;  Will crash, because the iterator is released after use, and *ite cannot find its address;


Vector code Example:

#include <iostream>using namespace std; #include <vector>//vector header file; #include <algorithm>//algorithm header file; int Main () {vector <int> vec (5,8);//--type is vector<int> the container vector contains a value of 5 int of type 8, and the variable is called VEC. Vector is a class template, so you must declare its type, int, all objects in a container must be of the same type;//define a container object; directly construct an array; use and arrays;/for (int i=0;i <vec.size (); i++)//size () is the number of elements currently in use in the container; {cout<<vec[i]<< "";}  Cout<<endl<<vec.size () << "<<vec.capacity" () <<endl;  Get the amount of space used in the container, and the total size; Vector<int>::iterator ite;  An iterator defining a vector, equivalent to defining a pointer; for (Ite=vec.begin (); Ite!=vec.end (); ite++)//Get started, end {cout<<*ite << "";  The iterator returns a reference:} cout<<endl;//at the end of the insert; Vec.push_back (9); VS6.0 expansion of space is twice times, in VS2005 expansion of space is 1.5 times times, for (Ite=vec.begin (); Ite!=vec.end (); ite++)//Get start, end {Cout<<*ite << " ";} Cout<<endl<<vec.size () << "" <<vec.capacity () <<endl;//tail Delete, capacity unchanged "Capacitty", However, the use of space to reduce one, once the capacity increases will not decrease; Vec.pop_back (); for (Ite=vec.begin (); ite!=vec.end (); ite++)//Get start, end {Cout<<*ite << "";}  Cout<<endl<<vec.size () << "<<vec.capacity () <<endl;vec.push_back (88); Vec.push_back (99); The capacity is just enough; for (Ite=vec.begin (); Ite!=vec.end (); ite++)//Get start, end {Cout<<*ite << "";} Cout<<endl<<vec.size () << "" <<vec.capacity () <<endl;ite = Find (Vec.begin (), Vec.end (),   88);  Find this element; Vec.erase (ITE); Use an iterator pointer to delete this element; for (int i=0;i<vec.size (); i++)//size () refers to the number of elements currently used in the container;{cout<<vec[i]<< "";  Cout<<endl<<vec.size () << "<<vec.capacity" () <<endl; Get the amount of space used in the container, and the total size; Vec.clear (); Just clear the data, there is no reclaim space, space until the end of the life of the object to recycle,//Use space is 0, but the capacity of space is still, only when the destructor is called when the space will be recycled; for (int i=0;i<vec.size (); i++)//size () refers to the current number of elements in the container that are used;{cout<<vec[i]<< ""; Cout<<endl<<vec.size () << "<<vec.capacity () <<endl;ite=find (Vec.begin (), Vec.end (),  Vec.insert (ite,2,77); Insert data before the position of the iterator tag; <span style= "color: #ff0000;" >//cout<<*ite<<endl; Will crash, because the iterator is released after use, *ite can not find its address,//and the use of the same vector, but the list of linked list is different, its iterator after use will continue to use, the list is unique; </span>for (int i=0;i< Vec.size (); i++) {cout<<vec[i]<< "";} Cout<<endl<<vec.size () << "<<vec.capacity () <<endl;system (" pause "); return 0;}
Operation Result:

List code example:

#include <iostream> #include <list> #include <algorithm>using namespace Std;int main () {List<char > lit; As with vectors,//list is a class template, Template,char is the type of the object in the list, lit is an object that is created, or the linked list can be inserted at both ends, and is bidirectional; Lit.push_back (' a '); Lit.push_back ( ' B '); Lit.push_front (' d '); Lit.push_front (' E '); Lit.push_front (' F '); Lit.push_front (' B '); Lit.push_front (' B '); list  <char>::iterator it;  Define a list of iterators, similar to a carton list of pointers, but better than the general use of pointers, which used a lot of heavy-duty operation; List<char>::iterator it1;  List<char>::iterator it2; For (It=lit.begin (); It!=lit.end (); it++) {cout<<*it<< "";}  cout<<endl;//-----------Linked list can be removed from both ends-------------------lit.pop_back (); Lit.pop_front (); for (It=lit.begin (); It!=lit.end (); it++) {cout<<*it<< "";}  cout<<endl;//-------------Delete all a---------------------------------//lit.remove (' a '); Delete all a;for (It=lit.begin (); It!=lit.end (); it++) {cout<<*it<< "";}  cout<<endl;//-------------Remove a continuous and identical a, leaving only one;--------------------------------Lit.unique (); Remove a continuous and identical a, with only one left; for(It=lit.begin (); It!=lit.end (); it++) {cout<<*it<< "";} Cout<<endl;list<char> lit1;lit1.push_back (' G '); Lit1.push_back (' H '); Lit1.push_back (' I '); lit1.push_ Back (' K '), for (It1=lit1.begin (); It1!=lit1.end (); it1++) {cout<<*it1<< "";} cout<<endl;//-------------Insert a list into another linked list---------------------------------it1=find (Lit.begin (), Lit.end (), '  F '); First, find the position to insert, in the position of the previous insertion;////lit.splice (it1,lit1); Insert the second list into the first linked list; the merged list is gone because it is &;for (It=lit.begin (); It!=lit.end (); it++) {cout<<*it<< "";} cout<<endl;//------Insert an element in lit1 before it in the list lit it1; insert K before f-----//-----Take it down and the element is gone-------------------It=find (Lit.begin (), Lit.end (), ' F '), It1=find (Lit1.begin (), Lit1.end (), ' K '), Lit.splice (IT,LIT1,IT1);//------------- Insert a segment of the list into another linked list---------------------------------//Insert the character of the [it-----it1] Segment in the list lit1 in front of the lit it2 pointer; It=find (Lit1.begin () , Lit1.end (), ' H '), It1=find (Lit1.begin (), Lit1.end (), ' K '), It2=find (Lit.begin (), Lit.end (), ' f '); Lit.splice (it2,lit1 , it,it1); ----void Merge (LIST&Amp x);//merge X into *this body. The contents of two lists must be sorted by ascending merge first.   Lit.sort (); Merge and sort two sorts; Lit1.sort (); Lit.merge (lit1);//-----------The data in the list in reverse order---------------lit.reverse (); for (it= Lit.begin (); It!=lit.end (); it++) {cout<<*it<< "";} Cout<<endl;for (It1=lit1.begin (); It1!=lit1.end (); it1++) {cout<<*it1<< "";} Cout<<endl;system ("pause"); return 0;}

Operation Result:



C + + Three containers: The difference between list, vector and deque

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.