title: What's the relation between xpos and iterator in C++
body: <p>Let's say <code>xpos</code> is the return object of <code>std::basic_string::find</code> of type <code>size_type</code>, we can use <code>xpos</code> to access chars in a <code>std::string</code> by <code>some_string[xpos]</code>, and <code>xpos</code> itself could be used to represent the index of a char in a string, we can also directly print a <code>xpos</code></p>
  <pre><code>std::string s{&quot;012345678902&quot;};
  auto res = s.find('2');
  std::cout &lt;&lt; s[res] &lt;&lt; &quot; at &quot; &lt;&lt; res &lt;&lt; '\n';
  &gt;&gt;&gt;
  2 at 2
  </code></pre>
  <p>We could also use an <code>iterator</code> to access items in a container with operator <code>*</code>, but
  we can't directly print an <code>iterator</code> and we need to use <code>std::distance</code> to calculate the index. To my understanding, <code>xpos</code> and <code>iterator</code> are similar to some extent but definitely not the same thing. However, when I am using <code>std::basic_string::erase(iterator first, iterator last)</code>, <a href="https://en.cppreference.com/w/cpp/string/basic_string/erase" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/string/basic_string/erase</a> makes it clear that we need two <code>iterators</code> to remove all chars in the range <code>[first, last)</code></p>
  <pre><code>std::string s{&quot;012345678902&quot;};
  auto it = std::find(s.begin(), s.end(), '0');
  auto rit = std::find(s.rbegin(), s.rend(), '0');
  s.erase(it, rit.base()-1);
  std::cout &lt;&lt; s &lt;&lt; '\n';
  &gt;&gt;&gt;
  02
  </code></pre>
  <p>This works as expected. But when I use two <code>xpos</code> to replace <code>it</code> and <code>rit</code> above</p>
  <pre><code>std::string s{&quot;012345678902&quot;};
  s.erase(s.find('0'), s.find_last_of('0'));
  std::cout &lt;&lt; s &lt;&lt; '\n';
  &gt;&gt;&gt;
  02
  </code></pre>
  <p>This code works as good as the <code>iterator</code> version. This confused me, since <code>xpos</code> and <code>iterator</code> are not identical, why <code>xpos</code> could be used perfectly to replace <code>iterator</code> in the function <code>std::basic_string::erase(iterator first, iterator last)</code>? What's exactly the relation between <code>xpos</code> and <code>iterator</code>?</p>