C++ STL  iterator, a template class program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ template class as the iterator in C++ programming

To show: How to use the C++ template class iterator in C++ programming

 

// C++ STL iterator, template class

#include <iostream>

#include <iterator>

#include <vector>

#include <list>

using namespace std;

 

template<class ite>

// create a function of template class type...

void funct(ite i1, ite i2)

{

typedef iterator_traits<ite>::iterator_category cat;

cout<<"Test the iterator type..."<<endl;

cout<<typeid(cat).name()<<endl;

 

// print the container data

cout<<"The data: ";

while(i1 != i2)

{

iterator_traits<ite>::value_type p;

p = *i1;

cout<<p<<" ";

i1++;

};

cout<<endl<<endl;

};

 

int main(void)

{

// declare vector and list containers

vector<char> vec(9, 'T');

list<int> lst(8, 7);

 

// function call...

funct(vec.begin(), vec.end());

funct(lst.begin(), lst.end());

return 0;

}

 

Output examples:

 

Test the iterator type...

struct std::random_access_iterator_tag

The data: T T T T T T T T T

Test the iterator type...

struct std::bidirectional_iterator_tag

The data: 7 7 7 7 7 7 7 7

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index