1
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 29, 2016 at 0:12
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

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;
}
answered Dec 29, 2016 at 4:54
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.