Sequence Containers in C++
In this tutorial, we will learn about sequence containers in C++. What is the sequence containers and why we use it in?
What is Sequence Containers in C++
A sequence is a container that stores a finite set of objects of the same type in a linear organization. An array of names is a sequence. You would use one of the three sequence types–std::vector, std ::list, or std::deque –for a particular application depending on its retrieval requirements.
The std :: vector Class in sequence containers
An std :: vector is a sequence you can access at random. You can append entries to and remove entries from the end of the std ::vector without the undue overhead. Insertion and deletion at the beginning or in the middle of the std :: vector takes more time because they involve shifting the remaining entries to make room or to close up the deleted object space. An std :: vector is an array of contiguous objects with an instance counter or pointer to indicate the end of the container. Random access is a matter of using a subscript operation.
The std :: list Class
A std:: list is a sequence you can access bidirectionally. A std:: list enables you to perform inserts and deletion anywhere without undue performance penalties. Random access is simulated by forward or backward iteration to the target object. An std:: list consists of non-contiguous objects linked together with forward and backward pointers.
The std ::deque Class
An std:: deque is like an std:: vector except for an std:: deque allows fast inserts and deletes at the beginning, as well as the end, of the container. Random inserts and deletes take more time.
#include<iostream> #include<iomanip> #include<vector> #include<algorithm> using namespace std; int main() { int dim; std::cout<<"How many integers? "; std::cin>>dim; // --a vector of integers std::vector<int> vct; // -- insert values into the vector for( int i=0;i<dim;i++) vct.insert(vct.end(),std:: rand()); std::cout<<"\n -- unsorted --"; std::vector<int>::iterator iter; //redeclaration for(i=0, iter=vct.begin();iter<vct.end(); iter++,i++) { if((i%4)==0) std::cout<<"\n"; std::cout<<std::setw(8)<<*iter; } // --sort the array with the std sort algorithm std::sort(vct.begin(), vct.end()); std::cout<<"\n --sorted --"; for(i=0,iter =vct.begin(); iter <vct.end(); iter++,i++) { if((i%4)==0) std::cout<<"\n"; std::cout<<std::setw(8)<<*iter; } }
Output from program
how many integers? 8 -- unsorted -- 41 18467 6334 26500 19169 15724 11478 29358 -- sorted -- 41 6334 11478 15724 18467 19169 26500 29358
Also read:
Leave a Reply