How could an iterator be printed in C ++?

Suppose I declared a vector C++as follows:

vector<int>numbers = {4,5,3,2,5,42};

I can iterate through the following code:

for (vector<int>::iterator it = numbers.begin(); it!=numbers.end(); it++){
    // code goes here
}

Now I would like to talk about block coding for loop.

I can access and change any value using this iterator. let's say I want to increase each value by 10 and print. Thus, the code will look like this:

*it+=10;
cout << *it << endl;

I can print the address of the iterator and duplicate elements.

The iterator address can be printed:

cout << &it << endl;

The address of duplicate elements can be printed:

cout << &(*it) << endl;

But why couldn't the iterator print by doing the following:

cout << it <<endl;

At first, I thought that the convention was taken from the JAVAsecurity goal. But if so, why can I type in his address?

, ? , ?

+4
3

, . ? , , , , , .

, . ( - , .)

, ​​, print(Iterator); ( - , ), , . operator << , .

+4

, !

, . , ( ).

.

cout << it - v.begin();  

:

#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;
}

:

lower_bound at position 2
upper_bound at position 4

: , , .

...

+4

, ?

.

?

In principle, the compiler does not make it easier by default; you can try editing the compiler code! But this is too awesome!

If not, why?

Because he does not have a well-defined way of expressing this.

+2
source

Source: https://habr.com/ru/post/1599179/


All Articles