關於STL的equal_range的筆記

STL中的equal_range算法返回一個pair類型的值range,
vector<int> vec;
...//vec initialize
pair<vector<int>::iterator,vector<int>::iterator> range;
range = equal_range(vec.begin(),vec.end(),value);
       其中range.first是可以在不改變原來排序順序的情況下的可以插入value的最小迭代器位置,range.second是不改變原來排序順序的情況下的可以插入value的最大迭代器位置.
       實際情況是:如果vec中存在value,那麼range.first就是vec中的指向第一個value位置的迭代器,而range.second則是vec中指向第一個大於value的值的位置的迭代器.如果搜索值在容器中是最後一個值那麼range.second就是container.end().當vec中沒有value時,range返回一個0區間,也就是range.first=range.second=指向vec中第一個值大於value的位置的迭代器(可能爲vec.end,如果vec中所有值均小於value)。

在sgi上的描述。
Note that equal_range may return an empty range; that is, it may return a pair both of whose elements are the same iterator.
 Equal_range returns an empty range if and only if the range [first, last) contains no elements equivalent to value.
In this case it follows that there is only one position where value could be inserted without violating the range's
ordering, so the return value is a pair both of whose elements are iterators that point to that position.
http://www.cplusplus.com/reference/algorithm/equal_range/ 上的描述
If value is not equivalent to any value in the range, the subrange returned has a length of zero, with both iterators
pointing to the nearest value greater than value, if any, or to last, if value compares greater than all the elements
in the range.
(但是在《c++標準程序庫自修教程與參考手冊》上沒有找到相關的說明,按理說應該有,可能是自己瀏覽的太快沒看到。)
從上面可以看出,不論是vec中存在不存在value,如果要將value插入vec中,都可以從range.second位置插入(無論range.second是否指向), 但是用於其他用途時要考慮到容器中不存在value時的range.first = range.second的情況。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章