Sequence Containers: vectors, Lists, Dequeue| OOP in C++


Sequence Containers

The different Sequence Containers are:


Vector


Vector stores the elements in contiguous memory locations and allows direct access to any element using subscript operator[ ].
Important member functions of the vector class
back()-gives a reference to the last element.
begin()- gives a reference to the first element.
clear()- deletes all elements from a vector.
erase()- deletes specific element.
insert()- inserts element in the vector.
pop_back()- Adds an element to the end.
size()- gives the number of element in vector.
Program to store and read data from vector


#include<iostream.h>
int main()
{
vector <int> u; //create a vector
cout<<"\n Initial size"<<v.size();
int n;
cout<<"\n Enter 5 integers";
for(int i=0; i<5; i++)
{
cin>>n;
v.push_back(n);
}
cout<<"\n updated size"<<v.size;
vector<int>::iterator itr=v.begin();
itr=itr+2;//iterator at 3rd position
v.insert(itr, 11);
for(int i=0; i<v.size(); i++)
{
cout<<u[i]<<",";
}
}


List


List is a bidirectional, linear list, provides efficient implementation of insertion and deletion operations. A list can be accessed sequentially only.
Member function of list class.
back()- gives reference to the last element.
begin()- gives reference to the first element.
clear()- deletes all the elements.
erase()- deletes element as specified.
insert()- Inserts elements as specified.
merge()- merges two ordered list.
sort()- sorts the list.
pop_back()- deletes the last element.
pop_front()- adds an element to the front.
size()- gives the size of list.
Insert and display elements in a list


#include<iostream.h>
int main()
{
list <int> list1;
int n;
cout<<"\n enter 5 elements ";
for(int i=0; i<5; i++)
{
cin>>n;
list1.push_back(n);
}
list1.sort();
list<int>::iterator p;
for(p=list1.begin();p! =list1.end(); ++p)
{
cout<<*p<<",";
}
}


Maps


Map is a sequence of (key, value) pair, where a single value is associated with each unique key.
Maps Sequence Containers
Member function of the map class
begin()- gives reference to the first element.
clear()- deletes all elements from map.
end()- gives a reference to the first element.
clear()- deletes all elements from map.
end()- gives a reference to the end of the map.
erase()- deletes specific element.
find()- gives the location of specified element.
size()- gives the size.
Program to store and find element in a map.


int main()
{
map<string, int> phone;
String name;
int number;
cout<<"\n Enter 5 name-phone pairs";
for(int i=0; i<5; i++)
{
cin>>name;
cin>>number;
phone [name]=number;
}
cout<<"\n Enter name to be searched";
Cin<<name;
number=phone[name];
cout<<"\n The number is"<<number;
}

Custom Search

%d bloggers like this: