I was making a library program for trying to practice C++. I wanted to use a vector to store all the books, the books being a struct to hold the general things the books would have.
struct Book
{
string bookName; // book's name
string bookAuthor; // book's author
string bookID; // a random generated string
int bookType; // what type of book
};
The books in the library would be stored in a vector. To find one of these books I used a function that takes in a bookId parameter and uses it to find the book.
Book LibrarySystem::LocateBook(string bookId)
{
/* May not be the fastest search algorithm */
for (int i = 0; i <= mBooks.size(); i++)
{
Book result = mBooks[i];
if (bookId == mBooks[i].bookID)
{
return result;
}
else
{
cout << "FAILED TO FIND " + bookId << endl;
}
}
}
This works but I was wondering if it could be faster. Looking at it, I am going through it one by one checking if the bookId
is equal to the one provide in the parameter which seems slow.
I did do a small test to check if it all worked. I created a function:
string LibrarySystem::BookDataOutput(string bookId)
{
Book book = LocateBook(bookId);
string data =
"Book author: " + book.bookAuthor + "\n" +
"Book name: " + book.bookName + "\n" +
"Book type: " + to_string(book.bookType) + "\n" +
"Book Id: " + book.bookID;
return data;
}
Which outputs a single string with all the book's information. It uses LocateBook
to find the the book with the bookId
.
I run in main:
int main(int args, char* argv[])
{
/* Seed the random generator */
srand(time(NULL));
LibrarySystem library;
library.RegisterBook("Test1", "Test1", BOOK_TYPE::Adult, "test1");
cout << library.BookDataOutput("test1") << endl;
cin.get();
}
and the output is:
Book author: Test1
Book name: Test1
Book type: 5
Book Id: test1
Which matches all the information I provided.
1 Answer 1
Since your search is only by 1 parameter, a map<string,Book>
would work a lot better than a vector.
map<string,Book> mBooks;
string LibrarySystem::BookDataOutput(string bookId)
{
Book book = mBooks[bookId];
string data =
"Book author: " + book.bookAuthor + "\n" +
"Book name: " + book.bookName + "\n" +
"Book type: " + to_string(book.bookType) + "\n" +
"Book Id: " + book.bookID;
return data;
}