Posotion of the charachter in a string with an iterator

Hello!
I would like to define a position of one charachter in the string using only an iterator.

I have a function that takes an iterator and writes all charackters and their position in the string. The problem is that I dont know how to define a position of the charackter only with an iterator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;
void position( string::iterator & piks)
{

while piks<=3{
//int s= something that defines a position of the current iterator
cout<<*piks<","<<s<<endl;
piks++;
}
}

int main(){
string a ="Haus";
string::iterator piks;
piks=a.begin();

position(pisk);

}


It should print then:
H,0
a,1
u,2
s,3

Thank you for the help
An iterator is not required to keep track of its location relative to a container, so you can't interrogate it to learn that. You can find the distance between two iterators, though.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

int main(){
  string a ="Haus";
  string::iterator piks, start;
  piks=a.begin();
  
  while (piks!=a.end()){
    cout<<*piks<<","<< std::distance(a.begin(), piks) <<endl;
    piks++;}

}

}

Last edited on
Topic archived. No new replies allowed.