Sorting book title alphabetically

I tried to sort the titles of the books by using a for loop and if-else statement to sort it alphabetically. However, I am facing some errors under the returnlistofBooks methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
  #include "Bookshelf.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

voidBookshelf::voidBookshelf(vector <Book*> listofBooks){
	this->listofBooks = listofBooks;
}

void voidBookshelf::addBook()
{
	int ID;
	string Title;
	string Author;
	for (int i = 1; i <= 5; i++)
		{
			cout << "Book#"<< i << ":" << endl;
			cout << "Enter an ID:";
			cin >> ID;
			cout << "Enter a title:";
			cin >> Title;
			cout << "Enter an author:";
			cin >> Author;
			Book *mybook = new Book(ID, Title, Author); //book object
			listofBooks.push_back(mybook);
		}
	      
}



void returnListofBooks(int count, string name)
{
	Book temp; //error: no default constructor exists for class "Book"
	for (int i = 0; i < count; i++) 
	{
		for (int j = 0; j < count - i; j++) 
		{
			if (books[j].title > books[j + 1].title) //error: identifier 'books' is undefined.
			{
				temp = books[j];
				books[j] = books[j + 1];
				books[j + 1] = temp;
			}


		}
	}
}




int main(){

	voidBookshelf * myBookshelf = new voidBookshelf;

	myBookshelf->addBook();
	myBookshelf->returnListofBooks();
	

	return 0;



}
Last edited on
#include "Bookshelf.h"
me may need to see that.

vector <Book*> listofBooks
be careful with your memory management

voidBookshelf * myBookshelf = new voidBookshelf;
unnecessary dynamic memory allocation.

void returnListofBooks(int count, string name)
but that function doesn't return anything...

Book temp; //error: no default constructor exists for class "Book"
then don't try to call it.
This could be solved if you limit the scope of your variables
1
2
3
Book temp(books[j]);
books[j] = books[j + 1];
books[j + 1] = temp;
or better, call std::swap( books[j], books[j+1] );

1
2
3
		for (int j = 0; j < count - i; j++) 
		{
			if (books[j].title > books[j + 1].title)
out of bounds, i starts in 0, so you try to access book[count] in the last iteration

//error: identifier 'books' is undefined.
¿was that supposed to be a member function?
Last edited on
Topic archived. No new replies allowed.