Hi, I am relatively new to C++ and I am having problems sorting a set of items here is my code:
#include<iostream>
#include<sstream>
#include<string>
#include<iomanip>
#include<fstream>
#include<vector>
#include<string>
#include<cstring>
#include<set>
#include<algorithm>
using namespace std;
struct SimpsonChars
{
string firstname,lastname;
double firstnum,secondnum,thirdnum,fourthnum,fifthnum;
SimpsonChars(const string& lname = "", const string& fname = "", double first = 0, double second = 0, double third = 0,
double fourth = 0, double fifth = 0, double sixth = 0):lastname(lname),firstname(fname),firstnum(first),
secondnum(second),thirdnum(third),fourthnum(fourth),fifthnum(fifth){}
};
bool operator <(const SimpsonChars& sc1, const SimpsonChars& sc2) { return sc1.lastname < sc2.lastname; }
int main(int argc, char * argv[])
{
multiset<SimpsonChars> sc;
vector<string> v;
string firstname,lastname;
string Simpson;
string value;
double first,second,third,fourth,fifth;
while(getline(cin, Simpson))
v.push_back(Simpson);
vector<string> v2(v);
//replaces all the commas with spaces
for(vector<string>::size_type i = 0; i < v2.size(); i++)
for(vector<string>::size_type j = 0; j < v2[i].size(); j++)
if(v2[i][j] == ',')
v2[i][j] = ' ';
//inserts contents of the text file into a set
for(vector<string>::size_type i = 0; i < v2.size(); i++)
{
istringstream iss(v2[i]);
if(iss>>lastname && iss>>firstname && iss>>first && iss>>second && iss>>third && iss>>fourth && iss>>fifth)
sc.insert(SimpsonChars(lastname,firstname,first,second,third,fourth,fifth));
}
//prints out the set
for(set<SimpsonChars>::iterator it = sc.begin(); it != sc.end(); ++it)
cout<<endl<<it->lastname<<" "<<it->firstname<<" "<<it->firstnum<<" "<<it->secondnum<<" "<<it->thirdnum<<" "<<it->fourthnum<<" "<<it->fifthnum<<endl;
//sort(sc.begin(), sc.end(),operator<());//tried calling sort like this, but got a huge error
}
My program is suppose to read a text file using I/O Redirection containing names of Simpsons characters and 5 numbers following it. The format of the text file is something like
Simpson,Homer,1,2,3,4.412,5
I managed to get each individual item into a set, but I am having trouble sorting it. I have tried putting my sort function at the top of my program into struct and passing it into the set like so,
struct cmp
{
bool operator()(const SimpsonChars& sc1, const SimpsonChars& sc2) { return sc1.lastname < sc2.lastname; }
};
set<SimpsonChars,cmp> sc;
but it gives me a huge error. I can't see what I am doing wrong here, any help would be appreciated.