Showing posts with label STL. Show all posts
Showing posts with label STL. Show all posts

The power of 'typedef' in C++

C++ allows the definition of our own types based on other existing data types. We can do this using the keyword typedef, whose format is:

typedef existing_type new_type_name ;

where existing_type is a C++ fundamental or compound type and new_type_name is the name for the new type we are defining.

For example:
typedef char C;
typedef unsigned int WORD;
typedef char * pChar;
typedef char field [50];

There are many scenarios where using typedef's are very advantageous. The following program is written based on the reasons for using typedef's as defined by Herb Sutter in his book "More Exceptional C++"



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program showing the advantages of using typedefs in C++

#include<iostream>
#include<map>
#include<vector>
#include<list>
#include<assert.h>

using namespace
std;

//Comment/Uncomment as required
//#define USING_MAPS
#define USING_OTHER_STL

//5 - Portability: Useful if different users want to use different STL classes
#if defined USING_MAPS
typedef map<int,int> table; //1 - Typeability: table is easier to type
#else
//4 - Flexibility: In future you could replace a map by a vector for example
typedef vector<int> table;
//typedef list<int> table;
#endif

typedef
table::iterator tableIter;

//map<int,int> multiplicationTableTill10(int num); - not very readable
table multiplicationTableTill10(int num); //2 - Readability: Easier to read

int
main()
{

int
i = 1;
table t = multiplicationTableTill10(7);
for
(tableIter t_iter = t.begin(); t_iter != t.end(); ++t_iter, ++i)
{

#if defined USING_MAPS
cout<<"7 * "<<i<<" = "<<t[i]<<endl;
#elif defined USING_OTHER_STL
cout<<"7 * "<<i<<" = "<<*t_iter<<endl;
#else
assert(0);
#endif
}
return
0;
}


typedef
int Multiplier; //int is also now written as Multiplier

//This program creates a multiplication table of the number input from 1 to 10
table multiplicationTableTill10(int num)
{

table t;
tableIter t_iter;
//3 - Communication: Multiplier is more meaningful then int in the case below
for(Multiplier i = 1; i <= 10; i++)
{

#if defined USING_MAPS
t[i] = num * i;
#elif defined USING_OTHER_STL
t_iter = t.end();
t.insert(t_iter, num * i);
#else
assert(0);
#endif
}
return
t;
}






The Output is as follows:



More information on Typedefs:


Instantiating a Multimap inside a class

The following is a very simple example of Instantiating a Multimap. This example was posted as a result of a comment on the actual Multimap example here.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows use of multi-maps in a class
#include<iostream>
#include<map>
#include <string>

using namespace
std;

class
mapInstantiator
{

public
:
~
mapInstantiator();
void
createMultiMap(void);
void
insertElements(pair<string, int> element);
void
printer(void);
private
:
multimap<string, int> *phoneNums;
};


void
mapInstantiator::createMultiMap(void)
{

//Instantiate
phoneNums = new multimap<string, int>;
}


void
mapInstantiator::insertElements(pair<string, int> element)
{

phoneNums->insert(element);
}


void
mapInstantiator::printer(void)
{

cout<<"\n\nMultimap printer method"<<endl;
cout<<"Map size = "<<phoneNums->size()<<endl;
multimap<string, int>::iterator it = phoneNums->begin();
while
(it != phoneNums->end())
{

cout<<"Key = "<<it->first<<" Value = "<<it->second<<endl;
it++;
}
}


mapInstantiator::~mapInstantiator()
{

//Dont forget to delete the pointer
delete phoneNums;
}


int
main()
{

mapInstantiator aClass;
aClass.createMultiMap();

//Insert key, value as pairs
aClass.insertElements(pair<string, int>("Joe",123));
aClass.insertElements(pair<string, int>("Will",444));
aClass.insertElements(pair<string, int>("Joe",369));
aClass.insertElements(pair<string, int>("Joe",812));
aClass.insertElements(pair<string, int>("Will",4556));
aClass.insertElements(pair<string, int>("Smith",71));

aClass.printer();

return
0;
}


The Output is as follows:


Example of C++ STL 'pair' container

The pair container is a rather basic container. It can be used to store two elements, called first and second, and that's about it. To define a variable as a pair container, the header file must be included. 'pair' can do basic features like assignment and comparisons and has no further special features. It is, however, a basic ingredient of the abstract containers map, multimap and hash_map.

Lets look at the example now:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A simple example of C++ STL container 'pair'
#include<iostream>
#include<string>
#include<utility>

using namespace
std;

int
main()
{

pair<string, string> name("Zahid","Ghadialy"); //firstname, lastname
string custName = name.first+" "+name.second;
pair<string, int> customerNum(custName, 23456); //firstname, cust. no.
pair<int, int> customerAge(customerNum.second, 30); //cust. no., age

cout<<"Customer Full Name = "<<custName<<endl;
cout<<"Customer Number of "<<customerNum.first<<" is "<<customerNum.second<<endl;
cout<<"Age of Customer Number = "<<customerAge.first<<" is "<<customerAge.second<<endl;

//If we now want to increment say, age by 1
customerAge.second++;
cout<<"New age of Customer Number = "<<customerAge.first<<" is "<<customerAge.second<<endl;

return
0;
}

The output is as follows:


The problem with Maps in C++

The following discussion is from More Exceptional C++ By Herb Sutter:

Question 1:
a: What's wrong with the following code? How would you correct it?

map::iterator i = m.find( 13 );
if( i != m.end() )
{
const_cast( i->first ) = 9999999;
}

b: To what extent are the problems fixed by writing the following instead?

map::iterator i = m.find( 13 );
if( i != m.end() )
{
string s = i->second;
m.erase( i );
m.insert( make_pair( 9999999, s ) );
}

Consider a map named m that has the contents shown in Figure; each node within m is shown as a pair. I'm showing the internal structure as a binary tree because this is what all current standard library implementations actually use.

As the keys are inserted, the tree's structure is maintained and balanced such that a normal inorder traversal visits the keys in the usual less ordering. So far, so good.

But now say that, through an iterator, we could arbitrarily change the second entry's key, using code that looks something like the following:

1. a) What's wrong with the following code? How would you correct it?

// Example: Wrong way to change a

// key in a map m.

//

map::iterator i = m.find( 13 );

if( i != m.end() )

{

const_cast( i->first ) = 9999999; // oops!

}

Note that we have to cast away const to get this code to compile. The problem here is that the code interferes with the map's internal representation by changing the map's internals in a way that the map isn't expecting and can't deal with.

Example above corrupts the map's internal structure (see Figure). Now, for example, an iterator traversal will not return the contents of the map in key order, as it should. For example, a search for key 144 will probably fail, even though the key exists in the map. In general, the container is no longer in a consistent or usable state. Note that it is not feasible to require the map to automatically defend itself against such illicit usage, because it can't even detect this kind of change when it occurs. In Example above, the change was made through a reference into the container, without calling any map member functions.

A better, but still insufficient, solution is to follow this discipline: To change a key, remove it and reinsert it. For example:

b) To what extent are the problems fixed by writing the following instead?

// Example: Better way to change a key

// in a map m.

//

map::iterator i = m.find( 13 );

if( i != m.end() )

{

string s = i->second;

m.erase( i );

m.insert( make_pair( 9999999, s ) ); // OK

}

This is better, because it avoids any change to keys, even keys with mutable members that are significant in the ordering. It even works with our specific example. So this must be the solution, right?

Unfortunately, it's still not enough in the general case, because keys can still be changed while they are in the container. "What?" one might ask. "How can keys be changed while they're in the container, if we adopt the discipline of never changing key objects directly?" Here are two counterexamples:

Let's say the Key type has some externally available state that other code can get at—for example, a pointer to a shared buffer that can be modified by other parts of the system without going through the Key object. Let's also say that that externally available state participates in the comparison performed by Compare. Then making a change in the externally available state, even without the knowledge of the Key object and without the knowledge of the code that uses the associative container, can still change the relative ordering of keys. So in this case, even if the code owning the container tries to follow an erase-then-reinsert discipline, a key ordering change can happen at any time somewhere else and therefore without an erase-then-reinsert operation.

Consider a Key type of string and a Compare type that interprets the key as a file name and compares the contents of the files. It's obvious that even if the keys are never changed, the relative ordering of keys can still change if the files are modified by another process, or (if the file is shared on a network) even by a user on a different machine on the other side of the world.

For details see Item 8 of the book More Exceptional C++ By Herb Sutter



An example of C++ Multimap

The following is a simple example of C++ Multimap class.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows use of multi-maps
//We input multiple phone numbers for different people
#include<iostream>
#include<map>
#include <string>

using namespace
std;

//forward declaration
void printer(multimap<string, int> pN);

int
main()
{

multimap<string, int> phoneNums;

//Insert key, value as pairs
phoneNums.insert(pair<string, int>("Joe",123));
phoneNums.insert(pair<string, int>("Will",444));
printer(phoneNums);

//Insert duplicates
phoneNums.insert(pair<string, int>("Joe",369));
phoneNums.insert(pair<string, int>("Smith",567));
phoneNums.insert(pair<string, int>("Joe",888));
phoneNums.insert(pair<string, int>("Will",999));
printer(phoneNums);

//Checking frequency of different keys
cout<<"\n\nFrequency of different names"<<endl;
cout<<"Number of Phones for Joe = "<<phoneNums.count("Joe")<<endl;
cout<<"Number of Phones for Will = "<<phoneNums.count("Will")<<endl;
cout<<"Number of Phones for Smith = "<<phoneNums.count("Smith")<<endl;
cout<<"Number of Phones for Zahid = "<<phoneNums.count("Zahid")<<endl;

//Print all Joe from the list and then erase them
pair<multimap<string,int>::iterator, multimap<string,int>::iterator> ii;
multimap<string, int>::iterator it; //Iterator to be used along with ii
ii = phoneNums.equal_range("Joe"); //We get the first and last entry in ii;
cout<<"\n\nPrinting all Joe and then erasing them"<<endl;
for
(it = ii.first; it != ii.second; ++it)
{

cout<<"Key = "<<it->first<<" Value = "<<it->second<<endl;
}

phoneNums.erase(ii.first, ii.second);
printer(phoneNums);

return
0;
}


//This method prints the vector
void printer(multimap<string, int> pN)
{

cout<<"\n\nMultimap printer method"<<endl;
cout<<"Map size = "<<pN.size()<<endl;
multimap<string, int>::iterator it = pN.begin();
while
(it != pN.end())
{

cout<<"Key = "<<it->first<<" Value = "<<it->second<<endl;
it++;
}
}




The output is as follows:

Simulating FIFO behaviour with priority queues for equal priorities

In priority queue, the C++ specifications does not define the behaviour of the algorithms when equal-priority items are involved. It is assumed that the ordering is not important in case of a priority queue as long as the same priority items are in correct order as compared to other priorities. For a programmer though this can be important as he expects FIFO ordering for same priority items. To overcome the problem I mentioned in earlier program, we can add another item to get correct FIFO ordering for same priority items.

This is just one approach and there may be other approaches. Also notice that I have used a local variable which requires the order to be input. You can also use the static variable approach for this.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of slightly advanced priority queue making sure that
//along with priorities, queue functionality of FIFO is maintained
#include <iostream>
#include <string>
#include <vector>
#include <queue>

using namespace
std;

class
PrioritizedWord
{

private
:
int
m_prio;
string m_word;
int
m_order; //To set FIFO operation

public
:
explicit
PrioritizedWord()
{ }

explicit
PrioritizedWord(const std::string& word, const int priority = 0, const int order = 0):
m_word(word), m_prio(priority), m_order(order)
{ }

//Operator overloading for priority comparison
const bool operator <(const PrioritizedWord& pW) const
{

if
(m_prio == pW.m_prio)
return
(m_order > pW.m_order);
else
return
(m_prio < pW.m_prio);
}

//Operator overloading to print output
friend ostream& operator <<(ostream& out, const PrioritizedWord& pW)
{

out<<pW.m_word;
return
out;
}

int
getPrio(void)
{
return m_prio;}
string getWord(void)
{
return m_word;}
};


int
main()
{

priority_queue<PrioritizedWord> zahidQueue;

//Note the final order will not be the same as the specs do not
//define behaviour in case two numbers with equal priority exist
zahidQueue.push(PrioritizedWord("First", 23, 1));
zahidQueue.push(PrioritizedWord("Second", 23, 2));
zahidQueue.push(PrioritizedWord("Third", 23, 3));
zahidQueue.push(PrioritizedWord("Fourth", 51, 4));
zahidQueue.push(PrioritizedWord("Fifth", -1, 5));

cout<<"\n\nZahid Queue elements :"<<endl;
while
(!zahidQueue.empty())
{

cout<<zahidQueue.top()<<" "<<endl;
zahidQueue.pop();
}


return
0;
}



The output is as follows:

An example of bound C++ maps

The following example shows how to define a bound C++ map which can only contain maximum number of specified elements. This is just an approach and there will probably be better and more efficient approaches.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//The example below shows a bound map. In a general C++ map you
//can add as many elements as required. In this case there can
//only be 10 elements in the map. If you try adding more it will
//generate an error
#include<iostream>
#include<map>
#include<string>
#include<assert.h>

using namespace
std;

map<int, string> freq;
int
a[10]={0,0,0,0,0,0,0,0,0,0};

int
store_in_maps(string s)
{

int
i;
for
(i=0; i < 10; i++)
{

if
(a[i]==0)
break
;
}

if
(i==10)
{

cout<<"Sorry no more Ids available in the pool"<<endl;
assert(0);
}


a[i]=1;
freq[i] = s;
return
i;
}


int
remove_from_map(string s)
{

map<int, string>::const_iterator iter;
for
(iter=freq.begin(); iter != freq.end(); ++iter)
{

if
(iter->second == s)
break
;
}

if
(iter==freq.end())
{

cout<<"Cant find the string "<<s<<endl;
return
(-1);
}

a[iter->first]=0;
return
iter->first;
}



int
main()
{

store_in_maps("first");
store_in_maps("second");
store_in_maps("third");
store_in_maps("fourth");
store_in_maps("fifth");
store_in_maps("sixth");
store_in_maps("seventh");
store_in_maps("eighth");
store_in_maps("ninth");
store_in_maps("tenth");
remove_from_map("fifth");
store_in_maps("eleventh");
remove_from_map("zahid");
remove_from_map("fourth");

map<int, string>::const_iterator iter;
for
(iter=freq.begin(); iter != freq.end(); ++iter)
{

cout<<"First: "<<(iter->first)<<" Second: "<<(iter->second)<<"\t\tPool value: "<<a[iter->first]<<endl;
}


return
0;
}



The output of the program is as follows:

An example of advanced erase in C++ maps

The following example shows how to use erase in C++ maps


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows an example of how C++ maps erase work.
#include <iostream>
#include <map>

using namespace
std;

int
main ()
{

map<char,int> zgmap;
map<char,int>::iterator it,it_low,it_up;

zgmap['a']=1;
zgmap['b']=2;
zgmap['c']=3;
zgmap['d']=4;
zgmap['e']=5;
zgmap['g']=6;
zgmap['j']=7;
zgmap['n']=8;

it_low=zgmap.lower_bound ('c'); // it_low points to c
it_up=zgmap.upper_bound ('j'); // it_up points to n and not j

zgmap.erase(it_low,it_up); // erases all elements from c to j

//Print Map contents
cout<<"\n** Printing the zgmap contents **"<<endl;
for
( it=zgmap.begin() ; it != zgmap.end(); it++ )
{

cout << (*it).first << " => " << (*it).second << endl;
}


return
0;
}



The output of the program is as follows:

An example of C++ maps

The following example shows the working of C++ maps. This also has a simple example of union which is sometimes used in C and C++ programs


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows an example of how maps work.
//In maps, the first parameter is key and second value
//The keys in the map are automatically softed from lower to higher
#include<iostream>
#include<map>
#include<string>

using namespace
std;

//defining a union that is used with newMap_
union uu
{

char
c;
int
i;
}
u;

//Lets define two different maps
//The first parameter is key and second value
map<string, int> portMap_;
map<void *, uu> newMap_;

int
main()
{

//first entry in portmap
portMap_["first"] = 1;

//example of using the iterator
map<string, int>::const_iterator it;
string z = "second";
it = portMap_.find(z); //not in the map so wont be found
if(it == portMap_.end())
{

portMap_[z] = 22; //add second element
}

//Add thrid element directly
z = "third";
portMap_[z] = 12345;

//Add 4th element by insert
portMap_.insert(pair<string,int>("fourth", 4444));

//Add 5th element by insert
portMap_.insert(pair<string,int>("fifth", 5555));


cout<<"\n** Printing the portmap_ values **"<<endl;
for
(it = portMap_.begin(); it != portMap_.end(); ++it)
cout<<"Key = "<<it->first<<" Val = "<<it->second<<endl;

cout<<"\n** Removing fourth element **"<<endl;
z = "fourth";
it = portMap_.find(z);
portMap_.erase(it);

cout<<"\n** Printing the portmap_ values **"<<endl;
for
(it = portMap_.begin(); it != portMap_.end(); ++it)
cout<<"Key = "<<it->first<<" Val = "<<it->second<<endl;

//Playing with New Map
cout<<"\n\nCreating New Map whose key is a void pointer"<<endl;

uu u_val1, u_val2;
void
*val1, *val2;
u_val1.i = 70, val1 = &u_val1;
newMap_[val1]=u_val1;

val2 = val1;
map<void *, uu>::const_iterator it_new;
it_new = newMap_.find(val2);
if
(it_new != newMap_.end())
{

u_val2 = it_new->second;
cout<<"Note that since u_val2 is a union you can print i or c as required"<<endl;
cout<<"val2 = "<<val2<<" value.c = "<<u_val2.c<<endl;
cout<<"val2 = "<<val2<<" value.i = "<<u_val2.i<<endl;
}


return
0;
}



The output is as follows:

Simple example of Priority Queue

Here is a simple example of priority queue:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

//Example showing how simple priority queues work using C++

#include <iostream>

#include <string>

#include <vector>

#include <queue>



using namespace
std;



class
PrioritizedWord

{


private
:

int
m_prio;

string m_word;



public
:

explicit
PrioritizedWord()

{ }


explicit
PrioritizedWord(const std::string& word, const int priority = 0):

m_word(word), m_prio(priority)

{ }


//Operator overloading for priority comparison

const bool operator <(const PrioritizedWord& pW) const

{


return
(m_prio < pW.m_prio);

}


//Operator overloading to print output

friend ostream& operator <<(ostream& out, const PrioritizedWord& pW)

{


out<<pW.m_word;

return
out;

}


int
getPrio(void)

{
return m_prio;}

string getWord(void)

{
return m_word;}

};




int
main()

{


int
somenum = 2;

while
(somenum > 0)

{


priority_queue<PrioritizedWord> wordQueue, zahidQueue, *temp=NULL;

//Word Queue first time, Zahid Queue second time

if(somenum%2==0)

{


temp = &wordQueue;

}


else


{


temp = &zahidQueue;

}




//Note the final order will not be the same as the specs do not

//define behaviour in case two numbers with equal priority exist

temp->push(PrioritizedWord("First", 23));

temp->push(PrioritizedWord("Second", 23));

temp->push(PrioritizedWord("Third", 23));

temp->push(PrioritizedWord("Fourth", 51));

temp->push(PrioritizedWord("Fifth", -1));



cout<<"\n\nWord Queue elements (All elements lost):"<<endl;

while
(!wordQueue.empty())

{


cout<<wordQueue.top()<<" "<<endl;

wordQueue.pop();

}




cout<<"\n\nZahid Queue elements (Elements preserved):"<<endl;

if
(!zahidQueue.empty())

{


priority_queue<PrioritizedWord> tempQueue;

while
(!zahidQueue.empty())

{


PrioritizedWord &temppW = zahidQueue.top();

cout<<temppW<<" "<<endl;

tempQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));

zahidQueue.pop();

}


while
(!tempQueue.empty())

{


PrioritizedWord &temppW = tempQueue.top();

zahidQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));

tempQueue.pop();

}

}




cout<<"\n\nZahid Queue - Removing an element and leaving the rest"<<endl;

{


priority_queue<PrioritizedWord> tempQueue;

while
(!zahidQueue.empty())

{


PrioritizedWord &temppW = zahidQueue.top();



if
(temppW.getWord() != "Second")

{


tempQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));

zahidQueue.pop();

}


else


{


zahidQueue.pop();

break
;

}

}


while
(!tempQueue.empty())

{


PrioritizedWord &temppW = tempQueue.top();

zahidQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));

tempQueue.pop();

}

}




cout<<"\n\nZahid Queue elements after removal of element"<<endl;

while
(!zahidQueue.empty())

{


cout<<zahidQueue.top()<<" "<<endl;

zahidQueue.pop();

}


somenum--;

}




return
0;

}


The output is as follows:

More on Vector Manipulation

This is slightly advanced vector manipulation program


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows advanced vector manipulation
#include<iostream>
#include<vector>

using namespace
std;

//This method prints the vector
void printer(vector<int> v)
{

unsigned int
i;
cout << "Size = " << v.size() << endl;
cout << "Contents = ";
for
(i = 0; i <v.size(); i++)
cout<<v[i]<<" ";
cout<<endl;
}


//Overloaded method same as above but takes pointers
void printer(vector<int*> v)
{

unsigned int
i;
cout << "\nOverloaded Method " << endl;
cout << "Size = " << v.size() << endl;
cout << "Contents = ";
for
(i = 0; i <v.size(); i++)
cout<<*v[i]<<" ";
cout<<endl;
}


int
main()
{

vector<int> v1(5, 1);
cout<<"** Original **"<<endl;
printer(v1);

unsigned int
i;
//Modifying the list above
for(i = 0; i < v1.size(); i++)
v1[i] = i + 3;
cout<<"\n** Modified **"<<endl;
printer(v1);

vector<int>::iterator it;
//Inserting in the list after the first element '0' and after the 4th elem '9 9 9 9'
it = v1.begin();
it += 1;
v1.insert(it,0);
it = v1.begin(); //Crash if you dont do this
it += 5; //Because we inserted '0', 4th element has become 5th.
v1.insert(it, 4, 9);
cout<<"\n** After Insert **"<<endl;
printer(v1);

//Testing Pop back - removes element from the end
v1.pop_back();
v1.pop_back();
cout<<"\n** After couple of Pop back's **"<<endl;
printer(v1);

//New Vector
cout<<endl<<"\n********** NEW *************"<<endl;
vector<int*> v2;
int
*a=new int(5);
int
*b=new int(6);
int
*c=new int(7);
int
*d=new int(11);
v2.push_back(a);
v2.push_back(b);
v2.push_back(c);
printer(v2);
cout<<"\ntwo pop_back and a push_back"<<endl;
v2.pop_back();
v2.pop_back();
v2.push_back(d);
printer(v2);
cout<<"\nClear Vector two"<<endl;
v2.clear();
printer(v2);

return
0;
}




The output is as follows:

Basic Vector Manipulation

Here is an example of basic vector manipulation




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

//This program shows how to create vectors, check size and capacity,

//change the value of the elements and finally clear the vector

#include <iostream>

#include <vector>



using namespace
std;



int
main()

{


//Create a vector called vectorOne

vector<int> vectorOne; //Note size is 0

//Resize to 3 with default value 7

vectorOne.resize(3,7);

//Print the output to see the resize

cout<<"Test 1"<<endl;

for
(unsigned i=0;i<vectorOne.size();i++)

{


cout<<"Element: "<<i<<" Value: "<<vectorOne.at(i)<<endl;

}




//Resize further to 7 and new values default to 4

vectorOne.resize(7,4);

cout<<"\nTest 2"<<endl;

for
(unsigned i=0; i<vectorOne.size(); i++)

{


cout<<"Element: "<<i<<" Value: "<<vectorOne.at(i)<<endl;

}




//Check what the size and capacity of the vector is

cout<<endl;

cout<<"Size of vectorOne is: "<<vectorOne.size()<<endl;

cout<<"Capacity of vectorOne is: "<<vectorOne.capacity()<<endl;



//Lets modify the values of these vectors

for(unsigned i=0,j=22;i<vectorOne.size();i++,j+=i)

{


vectorOne.at(i)=j;

}




cout<<"\nTest 3"<<endl;

for
(unsigned i=0; i<vectorOne.size(); i++)

{


cout<<"Element: "<<i<<" Value: "<<vectorOne.at(i)<<endl;

}




//Use reserve to reallocate vectorOne with enough storage for 10 elements

vectorOne.reserve(10);

cout<<"\nSize of vectorOne is: "<<vectorOne.size()<<endl;

cout<<"Capacity of vectorOne is: "<<vectorOne.capacity()<<endl;



//Try resizing to 15 and dont add any default values for the new elements

vectorOne.resize(15);

cout<<"\nSize of vectorOne is: "<<vectorOne.size()<<endl;

cout<<"Capacity of vectorOne is: "<<vectorOne.capacity()<<endl;



//Remove all elements of the vector

vectorOne.clear();

cout<<"\nVector Cleared"<<endl;

cout<<"Size of vectorOne is: "<<vectorOne.size()<<endl;

cout<<"Capacity of vectorOne is: "<<vectorOne.capacity()<<endl;

cout<<endl;



return
0;

}


The output of the program is as follows:


Check out this stream