Contents  1-5  6-11  12-16  17-21  22-27   28-33  34 - 38  39-46  Projects   MFC

   Contact
   C
   C++
   Visual Basic
   Java
   JavaScript
   DHTML
   Style Sheets
   About
   Normalization
   Active X
   TDC Binding
   PHP
   Perl and CGI
   Flash
   XML
   SQL
   Chat
   MCSE
   Linux
   Cabling   
 

   
 
    
    

The vector container resembles a C++ array in that it holds objects of the same type, and that each of these objects
can be accessed individually. Vector containers are optimized to provide fast access to their elements by an index. 
(Be sure to study the requirements for objects that are stored in STL containers.) The
vector container is defined as
a template class, meaning that it can be customized to hold objects of any type.  A vector is great for accessing
objects in sequence, but it does not provide an efficient method of accessing objects randomly, outside of sequence. 
For random access, use some type of a map, multimap, set, or multiset container.

There are 2 arguments that go with a vector container.  One is class T, and as with all templates, this represent the type of objects  being stored in the elements of the vector.  The other argument is class A, the allocator class.  Allocators are memory managers responsible for memory allocation and deallocation of elements for containers.  Here's how we define vectors:

vector<int>  VectorOfInts;
vector<floats>  VectorOfFloats;

The vector class includes a constructor that accepts the number of elements in the vector as a parameter.  So to set up a vector of 100 monsters, you would declare:   vector<Monster>  MonsterMash(100);    Vectors include the size() method, to return the vector's number of elements.  That would be MonsterMash.size();  .  To assign objects to vectors, you would use the subscript operator just as you would with arrays:  MonsterMash[3] = Godzilla;  Accessor method access is also the same as with arrays:  MonsterMash[3].GetStrength();  Vectors can grow automatically when more elements are added to them than they can handle.

Here are some examples:

#include <iostream.h>
#include <vector>

using namespace std;

//Define a vector of integers. The template name is "vector".  The type of object
//it contains is "int". The fully specified container data type is "vector<int>".


void main() {

     vector<int> vec_one;

     int a = 10;   
     int b = 20;

     vec_one.push_back(a); 
//Add items at end of vector
     vec_one.push_back(15);
     vec_one.push_back(b);

    
// vec_one now contains three int values: 2, 10, -5

     unsigned int indx;

    
//Display int objects stored in the vector
     for(indx = 0; indx < vec_one.size(); indx++)
     {
         cout << vec_one[indx] << " ";
     }
     cout << endl;
}
// close main()
Output:   10 15 20

 

#include <iostream>
#include <string>
#include <vector>

using namespace std;
//------------------------------------------------------------------------------------------

class Employee
{
      public:
         //Two overloaded constructors
	 Employee();
	 Employee(const string & name, const int SSN);
	 Employee(const Employee & rhs);  //Copy constructor
	 ~Employee();
	 void	SetName(const string & name);
	 string	GetName()	const;
	 void	SetSSN(const int SSN);
	 int	GetSSN() const;
         //Overloaded assignment operator  
	 Employee & operator=(const Employee & rhs);
      private:
	 string EmpName;
	 long SocialSecNum;
};
//Two overloaded Employee constructor implementations
Employee::Employee()
: EmpName("New Employee"), SocialSecNum(666666666)
{ }
Employee::Employee(const string & name, const int SSN)
: EmpName(name), SocialSecNum(SSN)
{ }
//Copy constructor implementation
Employee::Employee(const Employee & rhs)
: EmpName(rhs.GetName()), SocialSecNum(rhs.GetSSN())
{}
//Destructor implementation
Employee::~Employee()
{}

//Accessor method definitions
void Employee::SetName(const string & name)
{  EmpName = name;  }
string Employee::GetName() const
{  return EmpName;  }
void Employee::SetSSN(const int SSN)
{  SocialSecNum = SSN;  }
int Employee::GetSSN() const
{  return SocialSecNum;  }

//Overloaded assignment operator definition
Employee & Employee::operator=(const Employee & rhs)
{
	EmpName = rhs.GetName();
	SocialSecNum = rhs.GetSSN();
	return *this;
}

//------------------------------------------------------------------------------------------
//Overload the ostream operator so that using it with an Employee object will display the object's SocialSecNum data member
ostream & operator<<(ostream & os, const Employee & rhs)
{
	os << rhs.GetName() << " has the social security number: " << rhs.GetSSN() << ".";
	return os;
}

//------------------------------------------------------------------------------------------
template<class T>
//Prototype for display vector properties function, needs to be a template since STL containers are implemented as such
void ShowVector(const vector<T>& v);    

//------------------------------------------------------------------------------------------
//Setup "TheCompany" to be a vector container of Employee objects
typedef vector<Employee> TheCompany;


//------------------------------------------------------------------------------------------
int main()
{
        //Create instances of Employee objects
	Employee GeorgeW("George W. Bush", 213459648);
	Employee JenniferLopez("Jennifer Lopez", 256489789);
	Employee MariahC("Mariah Carrey", 321569846);
	Employee DavidDuchovny("David Duchovny", 217985364);
        //Create an indefinite vector container of Employee objects called "SmallBusiness"
	TheCompany SmallBusiness;
	cout << "SmallBusiness:\n";
	ShowVector(SmallBusiness);
           //Create a vector container of Employee objects called "ACorporation" with 3 elements	
        TheCompany ACorporation(3);
	cout << "ACorporation(3):\n";
	ShowVector(ACorporation);
        //Store(Assign) the Employee objects to the vector container elements 
	ACorporation[0] = GeorgeW;
	ACorporation[1] = JenniferLopez;
	ACorporation[2] = MariahC;
	cout << "ACorporation(3) after assigning Employees:\n";
	ShowVector(ACorporation);
        //Though "ACorporation" was declared to have only 3 elements, we can use push_back to add a 4th
	ACorporation.push_back(DavidDuchovny);
	cout << "ACorporation() after added 4th Employee:\n";
	ShowVector(ACorporation);
        //Call accessor methods of the template class Employee object stored in vector element
	ACorporation[0].SetName("Bill Clinton");
	ACorporation[0].SetSSN(219645897);
	cout << "ACorporation() after Set\n:";
	ShowVector(ACorporation);
	return 0;
}
//------------------------------------------------------------------------------------------
// Display vector properties
template<class T>
void ShowVector(const vector<T>& v)
{
	cout << "max_size() = " << v.max_size();
	cout << "\tsize() = " << v.size();
	cout << "\tcapacity() = " << v.capacity();
	cout << "\t" << (v.empty()? "empty": "not empty");
	cout << "\n";
	for(int i = 0; i < v.size(); ++i)
        {
            //Remember, we overloaded the << operator to display the SocialSecNum data member of an Employee object
	    cout << v[i] << "\n";
        }
	cout << endl;
}
Output:

SmallBusiness:
max_size() = 214748364 size() = 0 capacity() = 0 empty

ACorporation(3):
max_size() = 214748364 size() = 3 capacity() = 3 not empty
New Employee has the social security number: 666666666.
New Employee has the social security number: 666666666.
New Employee has the social security number: 666666666.

ACorporation(3) after assigning Employees:
max_size() = 214748364 size() = 3 capacity() = 3 not empty
George W. Bush has the social security number: 213459648.
Jennifer Lopez has the social security number: 256489789.
Mariah Carrey has the social security number: 321569846.

ACorporation() after added 4th Employee:
max_size() = 214748364 size() = 4 capacity() = 6 not empty
George W. Bush has the social security number: 213459648.
Jennifer Lopez has the social security number: 256489789.
Mariah Carrey has the social security number: 321569846.
David Duchovny has the social security number: 217985364.

ACorporation() after Set
:max_size() = 214748364 size() = 4 capacity() = 6 not empty
Bill Clinton has the social security number: 218976452.
Jennifer Lopez has the social security number: 256489789.
Mariah Carrey has the social security number: 321569846.
David Duchovny has the social security number: 217985364.

 

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
template<class T>

//The class "PrintMe" is a template class as declared above
class PrintMe
{
      public:
         //Overload () operator to display t
	 void operator()(const T & t)
	 {
		cout << t << " ";
	 }
};
int main()
{
        int NumberOfItems = 10;

	PrintMe<int>  DisplayInt;
	vector<int>   VectorOfInts(NumberOfItems);
	for(int i = 0; i < NumberOfItems; ++i)
	    VectorOfInts[i] = i * 2;
	cout << "Using the for_each() method:  ";

	for_each(VectorOfInts.begin(), VectorOfInts.end(), DisplayInt);

	cout << "\n";
	return 0;
}
Output:   Using the for_each() method:  0 2 4 6 8 10 12 14 16 18

 

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
template<class T>

//The class "PrintMe" is a template class as declared above
class PrintMe
{
      public:

              //Overload () operator to display t
	  void operator()(const T & t)
	  {
	       cout << t << " ";
	  }
};
int main()
{
        int NumberOfItems = 14;
        int Half = NumberOfItems / 2;
 
	PrintMe<int>	PrintInts;
	vector<int>	VectorOfInts(NumberOfItems);
	fill(VectorOfInts.begin(), VectorOfInts.begin() + Half, 1);
	fill(VectorOfInts.begin() + Half, VectorOfInts.end(), 2);
	for_each(VectorOfInts.begin(), VectorOfInts.end(), PrintInts);

	cout << "\n\n";
	return 0;
}
Output:   1 1 1 1 1 1 1 2 2 2 2 2 2 2


Member functions:

maxsize() - maximum number of elements allowed in a vector.
capacity() - tells how many elements a vector can hold.

size() - returns the number of items currently stored in the vector.

size_type size() const;

empty() - returns true if the number of elements is 0.

bool empty() const;

push_back -  returns an iterator that references a position just past the end of the vector.  For this method to work, the object class must define a copy constructor, 

void push_back(const T& x);

begin() - returns an iterator that references the beginning of the vector.

iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;

end() - returns an iterator that references a position just past the end of the vector.

iterator end();
const_iterator end() const;

erase() - remove specified elements from a vector.

vector<int> a;
a.erase(a.begin(), a.end());  
// Remove all elements.

clear() - erases (removes) all elements from a vector.

vector<int> a;
a.clear();     
 // Remove all elements.

Overloaded operators:  =,  ==,  and [ ] .

You will most probably need to create the following items for any class you use with a vector:

  • A default constructor
  • A copy constructor
  • An overloaded assignment operator

©2004 C. Germany