need help with sort in alphabetical order.

I need to have it sorted in the add function by alphabetical order. (not using vectors). so say the input is c a b then output would be a b c. right not it outputs in the same order as input. im using puTTY/unix compiler.

[code]
#include <iostream>
#include <string>
using namespace std;
const int SIZE=100;
class library
{
public:
library();//constructor
void add(string song);
void display();
private:
string title[SIZE];
int n;
};
library::library()
{
n=0;
}
void library::add(string song)
{

title[n++]=song;
}

void library::display()
{
for(int i=0;i<n;i++)
{
cout<<title[i]<<" "<<endl;//print items
}
cout<<endl;
}

int main() {
string song;
library songs;
char answer = 'Y';
while (toupper(answer) == 'Y') {
cout << "Enter a song title: " ;
getline(cin, song);
songs.add(song);
cout << "Do you wish to continue: ";
cin >> answer;
cin.ignore(); // removes the \n from input file stream
}
songs.display();

return 0;
}

Have a look at std::sort(). http://www.cplusplus.com/reference/algorithm/sort/

You're missing the [/code] at the end of your code segment.
Didn't change your code base. The code does what you want now.

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
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

constexpr unsigned short int SIZE = 100;

class library
{
  public:
    library();
    void add(string song);
    void display();
	
  private:
    string title[SIZE];
    unsigned short int n;
};

library::library() : n(0) { }

void library::add(string song)
{

	title[n++] = song;
	
	sort(title, title + n);
}

void library::display()
{
	for (unsigned short int i = 0; i < n; i++)
	{
		cout << title[i] << " " << endl;
	}
	
	cout << endl;
}

int main()
{
	string song_name;
	library songs;
	char answer = 'Y';
	
	while (toupper(answer) == 'Y')
	{
		cout << "Enter a song title: ";
		getline(cin, song_name);
		songs.add(song_name);
		
		cout << "Do you wish to continue: ";
		cin >> answer;
		cin.ignore();
	}
	
	songs.display();

	return 0;
}

Though, it would be more efficient if a seperate function in the library class was created for sorting the elements in the string. Instead of sorting it every time another song is added, that function could be called right before displaying the songs.
Last edited on
Topic archived. No new replies allowed.