What’s the relation between xpos and iterator in C++

  c++, iterator, string

Let’s say xpos is the return object of std::basic_string::find of type size_type, we can use xpos to access chars in a std::string by some_string[xpos], and xpos itself could be used to represent the index of a char in a string, we can also directly print a xpos

std::string s{"012345678902"};
auto res = s.find('2');
std::cout << s[res] << " at " << res << 'n';
>>>
2 at 2

We could also use an iterator to access items in a container with operator *, but
we can’t directly print an iterator and we need to use std::distance to calculate the index. To my understanding, xpos and iterator are similar to some extent but definitely not the same thing. However, when I am using std::basic_string::erase(iterator first, iterator last), https://en.cppreference.com/w/cpp/string/basic_string/erase makes it clear that we need two iterators to remove all chars in the range [first, last)

std::string s{"012345678902"};
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 << s << 'n';
>>>
02

This works as expected. But when I use two xpos to replace it and rit above

std::string s{"012345678902"};
s.erase(s.find('0'), s.find_last_of('0'));
std::cout << s << 'n';
>>>
02

This code works as good as the iterator version. This confused me, since xpos and iterator are not identical, why xpos could be used perfectly to replace iterator in the function std::basic_string::erase(iterator first, iterator last)? What’s exactly the relation between xpos and iterator?

Source: Windows Questions C++

LEAVE A COMMENT