Tuesday, 24 December 2013

C++ Vector Demo

#include<iostream>
#include<vector>
using namespace std;
void PrintVector(vector
&array)
{
cout << "Contents (" << "Size: " << (int)array.size() <<
" Max: " << (int)array.capacity() << ") - ";
for(int i = 0; i < (int)array.size(); i++)
{
cout << array[i] << " ";
}
cout << endl;
}

int main(int args, char **argc)
{
cout << "STL Vector Example" << endl;
cout << "Data Structures for Game Developers" << endl;
cout << "Allen Sherrod" << endl << endl;
vector
array;
array.reserve(5);
array.push_back(10);
array.push_back(20);
array.push_back(30);
array.push_back(40);
cout << " Inserted into vector. ";
PrintVector(array);
array.pop_back();
array.pop_back();
cout << "Popped two from vector. ";
PrintVector(array);
array.clear();
cout << " Cleared vector. ";
PrintVector(array);
cout << endl;
if(array.empty() == true)
cout << "Vector is empty.";
else
cout << "Vector is NOT empty.";
cout << endl << endl;
return 1;
}


the demo application creates an integer array and populates it with data using the push_back()method . The container is empty until items are pushed onto it. Once on the list, the array [] operators can be used to access the element by reading or writing to it. In the example code four items are pushed onto the list before popping  (removal) of the last two and displaying the contents of the container.
The container is cleared, displayed again, and tested to see if it is empty. Inside
the function used to print a container, the code uses size()to determine how many
valid elements are currently pushed onto the container while capacity()is used to
determine how much space the container can hold without being resized. To access
the elements, we use the array operators [] for convenience.
Share it Please

0 comments:

Post a Comment

Copyright @ 2013 Learn About Computers and Programming. Designed by Templateism | Love for The Globe Press