Yes, you can use binary search with custom data structures in C++. The key is to ensure your custom data structure supports random access iterators and is sorted according to the criteria you want to search by.
Assume you have a custom Player
struct, and you want to perform binary search based on the player's name:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Player {
std::string Name;
int Score;
};
bool comparePlayers(
const Player& a, const Player& b) {
return a.Name < b.Name;
}
int main() {
std::vector<Player> Players{
{"Aragorn", 100},
{"Legolas", 95},
{"Gimli", 80},
{"Frodo", 90}
};
// Sort the vector of Players
std::sort(
Players.begin(),
Players.end(),
comparePlayers
);
// Player to search for
Player target{"Legolas", 0};
// Perform binary search
bool found = std::binary_search(
Players.begin(),
Players.end(),
target,
comparePlayers
);
std::cout << "The player Legolas "
<< (found ? "was" : "was not") << " found";
}
The player Legolas was found
comparePlayers
to specify how to compare Player
objects based on their names.std::sort()
with the custom comparator to sort the vector of players.std::binary_search()
with the same comparator to search for the target player.When dealing with complex comparisons or multiple criteria, ensure your comparator function aligns with the sorting order. If you need to find the exact object or its position, use std::lower_bound()
or std::upper_bound()
:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Player {
std::string Name;
int Score;
};
bool comparePlayers(
const Player& a, const Player& b) {
return a.Name < b.Name;
}
int main() {
std::vector<Player> Players{
{"Aragorn", 100}, {"Legolas", 95},
{"Gimli", 80}, {"Frodo", 90}
};
std::sort(
Players.begin(),
Players.end(),
comparePlayers);
Player target{"Legolas", 0};
auto it = std::lower_bound(
Players.begin(),
Players.end(),
target,
comparePlayers
);
if (it != Players.end() &&
it->Name == target.Name) {
std::cout << "Object found: " << it->Name;
} else {
std::cout << "Object not found";
}
}
Object found: Legolas
By ensuring your data structure supports random access and using a custom comparator, you can effectively use binary search with custom data types.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the advantages of binary search, and how to use it with the C++ standard library algorithms binary_search()
, lower_bound()
, upper_bound()
, and equal_range()