Trying to make a simple program to catalogue books. Something like this, for example:
struct book{
string author;
string title;
int catalogNumber;
}
Ultimately, I want to be able to do title searches based on a range. So the user could specify to display results of books where the title begins with “aa” though “be”. Ideally, the search average case would be logarithmic.
Is there something in the STL that could help me? Otherwise, what is the best way to go about this?
Thanks!
You can store them in an
std::set, and usestd::lower_boundandstd::upper_boundto find a range (and yes, that should be logarithmic). To do that, you’ll need to defineoperator<to operate on just the field(s) you care about (title, in this case).If you’re (virtually) always treating the title as the key, you might prefer to use an
std::map<std::string, info>, withinfodefined like:This makes a few operations a little easier, such as:
If you want to support searching by title or author (for example) consider using something like a Boost bimap or multi_index.
For what it’s worth, I’d also give serious thought to using a
stringinstead of anintfor the catalog number. Almost none of the standard numbering systems (e.g., Dewey decimal, library of congress, ISBN) will store very nicely in an int.