简体   繁体   English

C ++ STL,常量迭代器,find()

[英]C++ STL, constant iterators, find()

I'm currently learning STL and I got some uncertainities about find and const iterators. 我目前正在学习STL,我对find和const迭代器有一些不确定性。 Let's say I have a find function: 假设我有一个find函数:

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. 在那之后,我应该检查我在另一个const_iterator中found ,或者对一个迭代器进行检查是否有效。 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? 第一个看起来更准确(至少对我而言),但第二个应该也能正常工作,对吗?

All standard library containers satisfy the requirement that Container::iterator is convertible to Container::const_iterator . 所有标准库容器都满足Container::iterator可转换为Container::const_iterator So both comparisons are valid and will yield the same result. 因此,两种比较都是有效的,并且会产生相同的结果。

From §23.2.1 - Table 96 §23.2.1 - 表96

X::iterator ... any iterator category that meets the forward iterator requirements. X::iterator ...满足前向迭代器要求的任何迭代器类别。 convertible to X::const_iterator . 可转换为X::const_iterator

Checking if your iterator is different from myContainer.end() is fine. 检查你的迭代器是否与myContainer.end()不同。 cend and cbegin methods are only here to explicitely obtain const iterators, so that makes no difference in your case. cendcbegin方法,这里只是为了明确地获得常量迭代器,这样就使得你的情况没有什么区别。

Note that you could do auto found = myContainer.find(value) in c++11 to infer the iterator type, and that some people will argue that Standard library is the correct name (not STL). 请注意,您可以在c ++ 11中执行auto found = myContainer.find(value)来推断迭代器类型,并且有些人会认为标准库是正确的名称(而不是STL)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM