std::binary search (tsz. std::binary searches)
std::binary_search
?A std::binary_search
egy algoritmus a <algorithm>
könyvtárban, amely gyorsan megmondja, hogy egy adott érték megtalálható-e egy rendezett tartományban (például vektorban vagy tömbben).
bool result = std::binary_search(begin, end, value);
begin
és end
– a rendezett tartomány határaivalue
– a keresett értéktrue
, ha megtalálta, false
, ha nem.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers = {1, 3, 5, 7, 9, 11};
int keresett = 7;
if (binary_search(numbers.begin(), numbers.end(), keresett)) {
cout << "A(z) " << keresett << " benne van a sorozatban." << endl;
} else {
cout << "A(z) " << keresett << " nincs benne a sorozatban." << endl;
}
}
A(z) 7 benne van a sorozatban.
Algoritmus | Mire való? |
---|---|
binary_search()
|
Megmondja, hogy létezik-e egy érték a rendezett sorozatban |
lower_bound()
|
Megadja az első pozíciót, ahol az érték beszúrható |
upper_bound()
|
Megadja az első pozíciót, ami nagyobb a keresett értéknél |