Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does string::find return size_type and not an iterator?

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?

like image 618
Frank Avatar asked Jun 17 '10 13:06

Frank


People also ask

Are iterators part of STL?

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.

What are the STL iterators?

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 (*).

What are the STL iterators and what is their purpose?

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.

What is the use of iterator while using containers justify with an example?

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.


1 Answers

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.

like image 109
sbi Avatar answered Oct 11 '22 18:10

sbi