C++ STL iterator, operator!= 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, operator!= to test if the iterator object on the left side of the operator is not equal to the iterator object on the right side in C++ programming

To show: How to use the C++ iterator, operator!= to test if the iterator object on the left side of the operator is not equal to the iterator object on the right side in C++ programming

 

// C++ STL iterator, operator!=

#include <iterator>

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

int i;

// vector container

vector<int> vec;

// vector iterator

vector<int>::iterator veciter;

 

// insert/push data into vector

for(i = 1; i<=10; ++i)

vec.push_back(i);

 

// print the data

cout<<"The vector vec data: ";

for(veciter = vec.begin(); veciter != vec.end(); veciter++)

cout<<*veciter<<" ";

cout<<endl;

 

// initializing reverse_iterators to the last element

vector<int>::reverse_iterator rvecpos1 = vec.rbegin(), rvecpos2 = vec.rbegin();

cout<<"The iterators rvecpos1 and rvecpos2 points to the first element in the reversed sequence: "<<*rvecpos1<<endl;

cout<<"\nOperation: rvecpos1 != rvecpos2"<<endl;

if(rvecpos1 != rvecpos2)

cout<<"The iterators are not equal."<<endl;

else

cout<<"The iterators are equal."<<endl;

rvecpos1++;

cout<<"\nThe iterator rvecpos1 now points to the second element in the reversed sequence: "<<*rvecpos1<<endl;

cout<<"\nOperation: rvecpos1 != rvecpos2"<<endl;

if(rvecpos1 != rvecpos2)

cout<<"The iterators are not equal."<<endl;

else

cout<<"The iterators are equal."<<endl;

return 0;

}

 

Output examples:

 

The vector vec data: 1 2 3 4 5 6 7 8 9 10

The iterators rvecpos1 and rvecpos2 points to the first element in the reversed sequence: 10

Operation: rvecpos1 != rvecpos2

The iterators are equal.

The iterator rvecpos1 now points to the second element in the reversed sequence: 9

Operation: rvecpos1 != rvecpos2

The iterators are not equal.

Press any key to continue . . .

 

 

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