In C++, why does string::find
return size_type
and not an iterator
?
It would make sense because functions like string::replace
or string::insert
take iterators as input, so you could find
some character and immediately pass the returned iterator to replace
, etc.
Also, std::find
returns an iterator -- why is std::string::find
different?
Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes.
In STL, an iterator is an object that can be used to traverse through or step through the elements in the container by using a set of operators like increment operator (++) or dereference operator (*).
Iterators are used to point at the memory addresses of STL containers. They are primarily used in sequences of numbers, characters etc. They reduce the complexity and execution time of the program.
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them.
The design of the standard library's shiny new string class was already done when Stroustrup introduced the standard committee to the STL. The committee liked the STL and started incorporating it into the standard, thereby adapting much of what they had already agreed on (and probably also delaying the standard for another year or two).
Among other changes, iterators were added to the already finished string class as an after-thought. You can see this by looking at the various string members taking/returning a position – it's a wild mix of indexes and iterators.
It's not always easy to guess why some member functions have only indices-taking versions and some have iterator-taking ones, too. In the case of std::basic_string<>::find()
, however, it seems easy: Since std::find()
already returns an iterator, std::basic_string<>::find()
was left as it was.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With