• upper_bound - return the position of exceeding value from key
  • lower_bound - return the position of same or first larger value than key
  • Target array or vector shall be in sorted condition.
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main(){
	vector<int> v;
	int a[5] = {1,2,2,2,3};
	for (int i=0; i<5; i++){
		v.push_back(a[i]);
	}
	int x=2;
	int c=(int)(upper_bound(v.begin(), v.end(), x) - lower_bound(v.begin(), v.end(), x));
	int f=(int)(lower_bound(v.begin(), v.end(), x) - v.begin());
	int t=(int)(upper_bound(v.begin(), v.end(), x) - v.begin());
	
	int f2= *lower_bound(v.begin(), v.end(), x);
	int t2= *upper_bound(v.begin(), v.end(), x);
	printf(" %d count : %d, starting : %d, ending : %d\n", x, c, f, t);
	printf(" lower bound start : %d, upper bound start : %d\n", f2, t2);
	
	c = (int) (upper_bound(a,a+5,x) - lower_bound(a,a+5,x));
	f = (int) (lower_bound(a,a+5,x) - a);
	t = (int) (upper_bound(a,a+5,x) - a);
	f2 = *lower_bound(a,a+5,x);
	t2 = *upper_bound(a,a+5,x);

	printf(" %d count : %d, starting : %d, ending : %d\n", x, c, f, t);
	printf(" lower bound start : %d, upper bound start : %d\n", f2, t2);
	
	return 0;
}
반응형

'Prog&Algol' 카테고리의 다른 글

BJ | 9996 | connect server when missing Korea  (0) 2022.03.29
BJ | 2309 | 일곱 난쟁이 | Combination  (0) 2022.03.22
Math | Sieve of Eratosthenes  (0) 2022.03.21
Math | Permutation & Combination  (0) 2022.03.21
Algo | C++ | priority Queue  (0) 2022.03.20

+ Recent posts