I have the following simple program that will binary_search for an item:
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
class Record
{
public:
Record() = default;
Record(std::string name, int data) : mName(name), mData(data) { }
std::string mName;
int mData = 0;
};
int main(int, char**)
{
std::vector<Record> recs;
recs.emplace_back(Record("1", 1));
recs.emplace_back(Record("55555", 2));
recs.emplace_back(Record("333", 3));
recs.emplace_back(Record("qwertyuiop", 4));
recs.emplace_back(Record("22", 5));
recs.emplace_back(Record("4444", 6));
std::cout << "Unsorted:" << std::endl;
for (auto& rec : recs)
{
std::cout << "Name: " << rec.mName << " Data: " << rec.mData << std::endl;
}
std::cout << std::endl;
std::stable_sort(recs.begin(), recs.end(), [](const Record& lhs, const Record& rhs) -> bool
{
return lhs.mName.length() < rhs.mName.length();
});
std::cout << "Sorted:" << std::endl;
for (auto& rec : recs)
{
std::cout << "Name: " << rec.mName << " Data: " << rec.mData << std::endl;
}
std::cout << std::endl;
if (std::binary_search(
recs.begin(),
recs.end(),
Record("qwertyuiop", 4),
[](const Record& lhs, const Record& rhs) -> bool
{
return lhs.mName < rhs.mName;
}))
{
std::cout << "Found" << std::endl;
}
else
{
std::cout << "Not found" << std::endl;
}
return 0;
}
How can I search the vector of Records based on another type of T? For example std::string instead of Record?
Something like:
if (std::binary_search(
recs.begin(),
recs.end(),
"qwertyuiop",
[](const Record& lhs, const std::string& rhs) -> bool
{
return lhs.mName < rhs.mName;
}))
{
std::cout << "Found" << std::endl;
}
else
{
std::cout << "Not found" << std::endl;
}
Is what I want - basically I don't want to construct a Record to search for it as this presents a performance issue for me.
You can create a function object type that handles heterogeneous comparisons:
struct comp_t
{
bool operator()(Record const& lhs, std::string const& rhs) const {
return lhs.mName < rhs;
}
bool operator()(std::string const& lhs, Record const& rhs) const {
return lhs < rhs.mName;
}
};
Then you can call binary_search
like this:
std::binary_search(recs.begin(), recs.end(),
std::string("qwertyuiop"),
comp_t{})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments