8

I'm currently learning STL and I got some uncertainities about find and const iterators. Let's say I have a find function:

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

After that should I check what I got for found against another const_iterator, or is it valid to make a check against simply an iterator. Basically would there be any difference between doing this:

if(found!=myContainer.cend())

and this:

if(found!=myContainer.end())

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

4

2 回答 2

10

所有标准库容器都满足Container::iterator可转换为Container::const_iterator. 所以这两个比较都是有效的,并且会产生相同的结果。

§23.2.1 - 表 96

X::iterator ...任何满足前向迭代器要求的迭代器类别。可转换为X::const_iterator.

于 2013-06-04T20:57:11.503 回答
1

检查您的迭代器是否与不同myContainer.end()是可以的。cendcbegin方法在这里只是为了显式地获取 const 迭代器,所以在你的情况下没有区别。

请注意,您可以auto found = myContainer.find(value)在 c++11 中推断迭代器类型,并且有些人会争辩说标准库是正确的名称(不是 STL)。

于 2013-06-04T20:56:20.917 回答