Property | Valid Expressions |
---|---|
An input iterator is a copy-constructible, copy-assignable and destructible. | X b(a); b= a; |
It can be compared by using a equality or inequality operator. | a==b; a!=b; |
It can be dereferenced. | *a; |
It can be incremented. | ++a; |
Where 'X' is of input iterator type while 'a' and 'b' are the objects of an iterator type.
An input iterator can be compared by using an equality or inequality operator. The two iterators are equal only when both the iterators point to the same location otherwise not. Suppose 'A' and 'B' are the two iterators
A ==B; // equality operator A!=B; // inequality operator
Let's see a simple example
#include <iostream> #include<vector> #include<iterator> using namespace std; int main() { vector<int> v{1,2,3,4,5}; vector<int>::iterator itr,itr1; itr=v.begin(); itr1=v.begin()+1; if(itr==itr1) std::cout << "Both the iterators are equal" << std::endl; if(itr!=itr1) std::cout << "Both the iterators are not equal" << std::endl; return 0; }
In the above example, itr and itr1 are the two iterators. Both these iterators are of vector type. The 'itr' is an iterator object pointing to the first position of the vector and 'itr1' is an iterator object pointing to the second position of the vector. Therefore, both the iterators point to the same location, so the condition itr1!=itr returns true value and prints "Both the iterators are not equal".
We can dereference an iterator by using a dereference operator(*). Suppose 'A' is an iterator
*A // Dereferencing 'A' iterator by using *.
Let's see a simple example:
#include <iostream> #include<vector> #include<iterator> using namespace std; int main() { vector<int> v{11,22,33,44}; vector<int>::iterator it; it = v.begin(); cout<<*it; return 0; }
In the above example, 'it' is an iterator object pointing to the first element of a vector 'v'. A dereferencing an iterator *it returns the value pointed by the iterator 'it'.
The two iterators pointing two different locations can be swapped.
Let's see a simple example.
#include <iostream> #include<vector> #include<iterator> using namespace std; int main() { vector<int> v{11,22,33,44}; vector<int>::iterator it,it1,temp; it = v.begin(); it1 = v.begin()+1; temp=it; it=it1; it1=temp; cout<<*it<<" "; cout<<*it1; return 0; }
In the above example, 'it' and 'it1' iterators are swapped by using an object of a third iterator, i.e., temp.