lower_bound 和 upper_bound的使用指南

#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vector
#include<functional>

//using namespace std;

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::sort(v.begin(), v.end());                // 10 10 10 20 20 20 30 30

	for (auto num : v)
		std::cout << num << " ";
	std::cout << std::endl;

	std::vector<int>::iterator low, up;
	low = std::lower_bound(v.begin(), v.end(), 20); //          ^
	up = std::upper_bound(v.begin(), v.end(), 20); //

	std::cout << "lower_bound at position " << (low - v.begin()) << '\n';
	std::cout << "upper_bound at position " << (up - v.begin()) << '\n';

	std::sort(v.begin(),v.end(),std::greater<int>());
	for (auto num : v)
		std::cout << num << " ";
	std::cout << std::endl; 
	//#include<functional> greater
	low = std::lower_bound(v.begin(), v.end(), 20,std::greater<int>()); //          ^
	up = std::upper_bound(v.begin(), v.end(), 20,std::greater<int>()); //

	std::cout << "lower_bound at position " << (low - v.begin()) << '\n';
	std::cout << "upper_bound at position " << (up - v.begin()) << '\n';



	system("pause");
	return 0;
}

 

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