I need to make s c++ code of sorting of book titles. 1. display the Inputted book titles. 2. display the book title in Alphabetical order. i was able to do the 1st but I'm having difficulty in displaying the alphabetical order of books. here's my code:
Instead of creating a C-style array to hold your book titles instantiate a std::vector object to hold a varying number of titles. You can then use the sort function in <algorithm>:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
template <typename T>
void DisplayContents(const T& Input);
int main()
{
std::vector<std::string> biblia;
biblia.push_back("A Tale of Two Cities");
biblia.push_back("Tales of An Ancient Empire");
biblia.push_back("1984");
biblia.push_back("The Hobbit");
biblia.push_back("Lord Of The Rings");
std::cout << "My original library:\n\n";
DisplayContents(biblia);
std::sort(biblia.begin(), biblia.end());
std::cout << "\nMy sorted library:\n\n";
DisplayContents(biblia);
}
template <typename T>
void DisplayContents(const T& Input)
{
for (auto iElement : Input)
{
std::cout << iElement << '\n';
}
std::cout << '\n';
}
My original library:
A Tale of Two Cities
Tales of An Ancient Empire
1984
The Hobbit
Lord Of The Rings
My sorted library:
1984
A Tale of Two Cities
Lord Of The Rings
Tales of An Ancient Empire
The Hobbit
If you want to use/create your own sort algorithm vector elements can be accessed using operator[], same as an array. Just change your function parameter list to pass a reference to a vector, no need to include the vector's size.
@FurryGuy
Thanks but how can i do it if i want to manually input the books? i'm not used in using vector. when i encounter this problem the first thing that comes to my mind is using array.
Your BubbleSort() takes a single string as the parameter. It needs to take an array: void BubbleSort(string books[], int size)
Making this change and doug4's change, the code works for me.
Enter a book name ("." to quit):
> Tales of An Ancient Empire
> A Tale of Two Cities
> 1984
> The Hobbit
> Lord of The Rings
> Learn C++ Vectors
> .
My original library (number of books: 6):
Tales of An Ancient Empire
A Tale of Two Cities
1984
The Hobbit
Lord of The Rings
Learn C++ Vectors
My sorted library (number of books: 6):
1984
A Tale of Two Cities
Learn C++ Vectors
Lord of The Rings
Tales of An Ancient Empire
The Hobbit