关于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的情况。

`std::equal_range`是C++ STL中的一个算法函数,用于在已排序的容器中查找某个值的范围。它返回一个pair对象,其中第一个元素是指向第一个等于给定值的元素的迭代器,第二个元素是指向第一个大于给定值的元素的迭代器。如果没有找到给定值,则这两个迭代器均指向第一个大于给定值的元素的位置。 以下是`std::equal_range`函数的函数原型: ```c++ template<class ForwardIt, class T> std::pair<ForwardIt, ForwardIt> equal_range(ForwardIt first, ForwardIt last, const T& value); template<class ForwardIt, class T, class Compare> std::pair<ForwardIt, ForwardIt> equal_range(ForwardIt first, ForwardIt last, const T& value, Compare comp); ``` 其中: - `first`和`last`表示要查找的元素范围,必须是已排序的。 - `value`表示要查找的值。 - `comp`是可选的,表示比较函数,用于比较元素的值,默认为`std::less<T>`。 下面是一个使用`std::equal_range`函数查找vector中某个值范围的例子: ```c++ #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 4, 4, 5, 6}; auto range = std::equal_range(v.begin(), v.end(), 4); std::cout << "Range of 4: [" << std::distance(v.begin(), range.first) << ", " << std::distance(v.begin(), range.second) << ")" << std::endl; return 0; } ``` 输出: ``` Range of 4: [3, 6) ``` 这表示4在vector中的范围是从下标3到下标6之间的元素(不包括下标6)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值