sorting vector of strings alphabetically

Hi, I'm trying to write a program that reads in from a .txt file the movie title, rating, director, actors etc. All I want to do is to just sort movie titles alphabetically and print all its attributes(director, actors). I tried using
sort( movies.begin(), movies.end()) method, but it doesn't work. Any advice on what I should do?

here's my code btw:
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
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include <iterator>
#include "Movie.h"

using namespace std;

//-------------------------------------
//Main program ------------------------
//-------------------------------------

int main () {
	vector<Movie> movies;
	ifstream fin("CS172_Spring2014_Movie_inputs.txt");
	ofstream fout("movie.txt");

	//read in file until end of file

	while ( !fin.eof() ) {
	string data;
	Movie movie;

	getline(fin, data, '\n'); //reads data from file
	movie.setTitle(data);     //sets next data to movie title
	
	
	//fin.ignore();			 
	
	getline(fin, data, '\n');  
	movie.setDirector(data);	//sets next data to Director
	//fin.ignore();
	
	getline(fin, data,'\n');
	int year = atoi(data.c_str());  //converts data string to int
	if(year==0)	{
		Movie_Rating rating = movie.rate_from_string(data); //converts and assigns string data to Movie_Rating type object
		movie.setRating(rating);							//sets next data to movie rating
	}
	else {
		movie.setYear(year);            //sets next data to year
	
	}//fin.ignore();
	
	getline(fin, data, '\n');
	year = atoi(data.c_str());
	if(year==0)	{
		Movie_Rating rating = movie.rate_from_string(data); //converts and assigns string data to Movie_Rating type object
		movie.setRating(rating);			
	}else {
		movie.setYear(year);
	}
	//sets next data to movie rating
	//fin.ignore();
	
	getline(fin, data, '\n');
	movie.setURL(data);      //sets next data to imdb URL
	
	getline(fin,data,'\n');
		//read actors in file until $$$$
		while( data != "$$$$"){
			movie.addActor(data); // sets next data to actors until $$$$ is encountered
			getline(fin,data,'\n');
		}
		movies.push_back(movie);
	}

	sort(movies.begin(), movies.end()); //sort the movie titles alphapetically
	
	for(int i=0; i< movies.size(); i++)	{
	movies[i].output(cout);     //print to screen
	movies[i].output(fout);     //print to movie.txt file
	}

	
	return 0; //program done
}
You'll need to specify the comparison function/class to use with the std::sort call.

http://www.cplusplus.com/reference/algorithm/sort/
Just a guess:

1
2
3
4
std::sort(movies.begin(), movies.end(), [](Movie const &a, Movie const &b) -> bool
{
    return a.getTitle() < b.getTitle();
});
Last edited on
Topic archived. No new replies allowed.