C++ STL  iterator, iterator_traits class for vector and list 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++ iterator_traits class for vector and list as a template helper struct used to specify all the critical type definitions that an iterator should have in C++ programming

To show: How to use the C++ iterator, iterator_traits class for vector and list as a template helper struct used to specify all the critical type definitions that an iterator should have in C++ programming

 

// C++ STL iterator, iterator_traits class for vector and list

#include <iterator>

#include <vector>

#include <iostream>

#include <list>

using namespace std;

 

int main()

{

// vectors and list containers

vector<int> vec1;

vector<char> vec2;

list<char> lst;

 

typedef iterator_traits<vector<int>::iterator>::iterator_category cati;

typedef iterator_traits<vector<char>::iterator>::iterator_category catc;

typedef iterator_traits<list<char>::iterator>::iterator_category catlst;

 

// both are random-access iterators

cout<<"The type of iterator for vector<int> is identified by the tag: "<<" "<<typeid(cati).name()<<endl;

cout<<"The type of iterator for vector<char> is identified by the tag: "<<" "<<typeid(catc).name()<<"\n";

cout<<"\nOperation: typeid(cati) == typeid(catc)"<<endl;

if(typeid(cati) == typeid(catc))

cout<<"The iterators type are the same."<<endl<<endl;

else

cout<<"The iterators type are not the same."<<endl<<endl;

 

// but the list iterator is bidirectional, not random access

cout<<"The type of iterator for list<char> is identified by the tag: "<<typeid(catlst).name()<<endl;

cout<<"\nOperation: typeid(vec1.begin())==typeid(vec2.begin())"<<endl;

if(typeid(vec1.begin()) == typeid(vec2.begin()))

cout<<"The iterators type are the same."<<endl;

else

cout<<"The iterators type are not the same."<<endl;

return 0;

}

 

Output examples:

 

The type of iterator for vector<int> is identified by the tag: struct std::random_access_iterator_tag

The type of iterator for vector<char> is identified by the tag: struct std::random_access_iterator_tag

Operation: typeid(cati) == typeid(catc)

The iterators type are the same.

The type of iterator for list<char> is identified by the tag: struct std::bidirectional_iterator_tag

Operation: typeid(vec1.begin())==typeid(vec2.begin())

The iterators type are not the same.

Press any key to continue . . .

 

 

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