C ++ STL, constant iterators, find ()

I am currently studying STL, and I have uncertainty in the search and constant iterators. Let's say I have a search function:

some_stl_container::const_iterator found = myContainer.find(value); 

After that, I have to check what I got for found , against another const_iterator, or is it valid to make a check against just an iterator. Basically, there will be some difference between this:

 if(found!=myContainer.cend()) 

and this:

 if(found!=myContainer.end()) 

The first one looks more accurate (at least for me), but the second should work fine, right?

+6
source share
2 answers

All standard library containers satisfy the requirement that Container::iterator be converted to Container::const_iterator . Thus, both comparisons are valid and will give the same result.

From ยง23.2.1 - Table 96

X::iterator ... any iterator category that matches the forward iterator of the requirement. converts to X::const_iterator .

+8
source

Checks if your iterator is different from myContainer.end() . cend and cbegin are only used here to explicitly get constant iterators, so that doesn't make any difference in your case.

Note that you can do auto found = myContainer.find(value) in C ++ 11 to indicate the type of iterator, and that some people will argue that the standard library is the correct name (and not STL).

+1
source

Source: https://habr.com/ru/post/946537/


All Articles