算法之旅,直奔<algorithm>之十二 equal_range

35 篇文章 1 订阅
29 篇文章 0 订阅

equal_range(vs2010)

  • 引言
这是我学习总结<algorithm>的第十二篇,equal_range很好理解,也很好用,适合排序以后的存在大量重复的数据。
  • 作用
equal_range的作用是
Get subrange of equal elements
Returns the bounds of the subrange that includes all the elements of the range  [first,last) with values equivalent to  val.
  • 原理
template <class ForwardIterator, class T>
  pair<ForwardIterator,ForwardIterator>
    equal_range (ForwardIterator first, ForwardIterator last, const T& val)
{
  ForwardIterator it = std::lower_bound (first,last,val);
  return std::make_pair ( it, std::upper_bound(it,last,val) );
}

  • 实验
对于数据集合
         
找到 20 的下限和上限,即是 3 和 6 

又例如倒序的数据集合
           
找到 20 的下限和上限,即是 2 和 5

             
  • 代码
test.cpp
#include <iostream>     // std::cout
#include <algorithm>    // std::equal_range, std::sort
#include <vector>       // std::vector
#include <iterator>

bool mygreater (int i,int j) 
{ 
	return (i>j); 
}

int main () 
{
	int myints[] = {10,20,30,30,20,10,10,20};
	std::vector<int> v(myints,myints+8);                         // 10 20 30 30 20 10 10 20
	std::pair<std::vector<int>::iterator,std::vector<int>::iterator> bounds;

	// using default comparison:
	std::sort (v.begin(), v.end());                              // 10 10 10 20 20 20 30 30
	bounds = std::equal_range (v.begin(), v.end(), 20);            //          ^        ^

	std::copy(v.begin(), v.end(),std::ostream_iterator<int>(std::cout," "));
	std::cout<<std::endl;
	std::cout << "bounds at positions " << (bounds.first - v.begin());
	std::cout << " and " << (bounds.second - v.begin()) << '\n';


	// using "mygreater" as comp:
	std::sort (v.begin(), v.end(), mygreater);                   // 30 30 20 20 20 10 10 10
	bounds = std::equal_range (v.begin(), v.end(), 20, mygreater); //       ^        ^
	std::copy(v.begin(), v.end(),std::ostream_iterator<int>(std::cout," "));
	std::cout<<std::endl;
	std::cout << "bounds at positions " << (bounds.first - v.begin());
	std::cout << " and " << (bounds.second - v.begin()) << '\n';
	system("pause");
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值