Sunday, January 8, 2012

Vector




In computing, sequence containers refer to a group of container class templates in the standard library of the C++ programming language that implement storage of data elements. Being templates, they can be used to store arbitrary elements, such as integers or custom classes. One common property of all sequential containers is that the elements can be accessed sequentially. Like all other standard library components, they reside in namespace std.

The following containers are defined in the current revision of the C++ standard: array, vector, list, forward_list, deque. Each of these containers implement a different algorithms for data storage, which means that they have different speed guarantees for different operations:[1]

array implements a compile-time non-resizeable array.
vector implements an array with fast random access and an ability to automatically resize when appending elements.
deque implements a double-ended queue with comparatively fast random access.
list implements a doubly linked list.
forward_list implements a singly linked list.

Running Codes
#include
#include
using namespace std;

// Display the vector contents by looping with size
void display(vector &v)
{
cout << endl;
for(int i=0;i<5;i++)
{
cout << v[i] << " ";
}
cout << endl;
}

// Display the vector contents by iterator
void show(vector &v)
{
cout << endl;
vector::iterator p;
for(p=v.begin();p!=v.end();p++)
{
cout << *p << " ";
}
cout << endl;
}


int main()
{
vector v;
// Initial Size : 0
cout << "Initial Size : " << v.size() << endl;

for(int i=0;i<10;i++)
{
// Insert at the back
v.push_back(i);
}
// Display
display(v);

v.pop_back(); // Pop from the back

cout << endl << v.front() << endl;

cout << endl << v.back() << endl;

// Display
display(v);

vector::iterator itr=v.begin(); // Get the iterator
itr+=3; // Iterator points to the 4th element
v.insert(itr,2,99); // Insert 99 twice into that position
display(v);

v.erase(v.begin()+3,v.begin()+5); // Remove 4th and 5th element
display(v);

v.erase(v.begin(),v.end()); // Remove all the elements
display(v);

cout << endl;

cin.get();
return 0;
}


http://www.cplusplus.com/reference/stl/vector/vector/

No comments:

Post a Comment