Hey guys,
I created a Student class in a header file and it works just fine. The problem is I'm trying to store the Student objects into a map in main which made the compiler generate a "in file included from ..." error. I'm having trouble fixing this problem as I do not know why the map is not accepting the object as a key. The following code is my Student class and main:
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <utility>
#include <string>
typedef std::pair<std::string, std::string> Name;
class Student {
public:
explicit Student(const std::string& id, const std::string& firstName, const std::string& lastName)
: id_(id), name_(toLowerString(firstName), toLowerString(lastName)){
if(!isValidId(id) || !isValidName(name_)){
throw "Student::Student(const string&, const string&, const string&): invalid input.";
}
}
Student() : id_(id_) {name_.first = name_.first; name_.second = name_.second;}
friend std::ostream& operator<<(std::ostream& os, const Student& s);
friend std::istream& operator>>(std::istream& is, Student& s);
private:
std::string id_;
Name name_;
static bool isValidName(const Name& name){
std::string::size_type i;
for(i = 0; i < name.first.size(); i++){
if(isspace(name.first[i]))
return false;
}
for(i = 0; i < name.second.size(); i++){
if(isspace(name.second[i]))
return false;
}
return true;
}
static bool isValidId(const std::string& id){
std::string::size_type i;
if(id[0] == 'a' && id.size() == 9){
for(i = 1; i < id.size(); i++){
if(!isdigit(id[i]))
return false;
}
return true;
}
return false;
}
static std::string toLowerString(const std::string& s){
std::string s1 = s;
for(std::string::size_type i = 0; i < s1.size(); i++){
s1[i] = tolower(s1[i]);
}
return s1;
}
};
inline std::ostream& operator<<(std::ostream& os, const Student& s){
return os << s.id_ << ' ' << s.name_.first << ' ' << s.name_.second << std::endl;
}
inline std::istream& operator>>(std::istream& is, Student& s){
std::string id;
Name name;
if(is >> id >> name.first >> name.second && Student::isValidId(id) && Student::isValidName(name)){
s.id_ = id;
s.name_.first = Student::toLowerString(name.first);
s.name_.second = Student::toLowerString(name.second);
} else
is.setstate(std::ios_base::failbit);
return is;
}
#endif
int main(){
string id;
Name name;
int score;
Student s(id, name.first, name.second);
map<Student, int> m;
cout << "Enter a valid id, first name, last name, and a score: ";
while(cin >> s >> score){
m[s] += score; <-problem occurs right here
cout << "Enter a valid id, first name, last name, and a score: ";
}
/*for(map<Student, int>::iterator it = m.begin(); it != m.end(); ++it){
cout << it->first.id_ << endl;
}*/
}
Any help would be appreciated. Assume that the header file and the main are in seperate files.
Thanks.