-2
예를 들어, 요소가 1,7,9,23,34,47,67,89,123,234,345,567 인 배열이 있습니다. 123의 위치를 알아야합니다.lower_bound (upper_bound)를 사용하여 배열에있는 숫자의 위치를 찾는 방법은 무엇입니까?
예를 들어, 요소가 1,7,9,23,34,47,67,89,123,234,345,567 인 배열이 있습니다. 123의 위치를 알아야합니다.lower_bound (upper_bound)를 사용하여 배열에있는 숫자의 위치를 찾는 방법은 무엇입니까?
요소가있는 배열을 선언하고 초기화하십시오. 그런 다음 int 중 vector
을 만듭니다. vector
에서 upper_bound()
을 사용하십시오. 다음은 예입니다.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
int arr[] = {1,7,9,23,34,47,67,89,123,234,345,567};
int len = sizeof(arr)/sizeof(arr[0]);
vector<int> v(arr,arr+len);
vector<int>::iterator upper;
upper = upper_bound(v.begin(), v.end(), 123);
cout<<(upper-v.begin())<<endl; // Output: 9
return 0;
}
희망이 있습니다.
배열에'std :: upper_bound'와'std :: lower_bound'를 직접 사용할 수 있습니다. 그 벡터가 필요 없습니다. –
['std :: find'] (http://en.cppreference.com/w/cpp/algorithm/find) 잘 작동해야합니다. 필요한 경우 iterator가 아닌 (수치) 인덱스를 얻기 위해'std :: begin (array)'를 뺄 수 있습니다. – Xirema
시도해 보셨습니까? [최소, 완전하고 검증 가능한 예제] (http://stackoverflow.com/help/mcve) – George