how the iterator in c++ could be printed?

Yes, there is a way to do it!

You can’t print the iterator because it is not defined to have a value.
But you can perform arithematic operations on them and that helps you to print the value (of the iterator).

Do the following.

cout << it - v.begin();  

Example:

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

using namespace std;

int main () {
  vector<int> v = {20,3,98,34,20,11,101,201};           
  sort (v.begin(), v.end());                

  vector<int>::iterator low,up;
  low = lower_bound (v.begin(), v.end(), 20);          
  up = upper_bound (v.begin(), v.end(), 20);                  

  std::cout << "lower_bound at position " << (low - v.begin()) << std::endl;
  std::cout << "upper_bound at position " << (up - v.begin()) << std::endl;

  return 0;
}

Output of the above code:

lower_bound at position 2
upper_bound at position 4

Note: this is just a way to get things done and no way I have claimed that we can print the iterator.

Leave a Comment

tech