我正在编写一个程序,它将读取带有社会安全号码(当然不是真正的)的名称列表,并根据姓氏或ssn对列表进行排序,具体取决于在命令行参数上。为了简单起见,我已经超载了运算符以及超载的输入和输出操作符。一切都编译好,直到我添加排序功能和输出在主的末尾。我很难过。有任何想法吗?任何其他提示也非常感谢。重载比较运算符来处理C++中的STL排序
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <fstream>
using namespace std;
enum sortVar { NAME, SOCSEC };
class record {
public:
friend bool operator<(record& rhs, record& name);
friend ostream& operator<<(ostream& out, record& toWrite);
friend istream& operator>>(istream& in, record& toRead);
bool t_sort;
private:
string firstName, lastName, ssn;
};
bool operator<(record& rhs, record& next)
{
if (rhs.t_sort = false) {
if (rhs.lastName == next.lastName)
return rhs.firstName < next.firstName;
else
return rhs.lastName < next.lastName;
}
else if (rhs.t_sort = true)
return rhs.ssn < next.ssn;
}
ostream& operator<<(ostream& out, record& toWrite)
{
out << toWrite.lastName
<< " "
<< toWrite.firstName
<< " "
<< toWrite.ssn;
}
istream& operator>>(istream& in, record& toRead)
{
in >> toRead.lastName >> toRead.firstName >> toRead.ssn;
}
int main(int argc, char* argv[])
{
if (argc !=3) {
cerr << "Incorrect number of arguments.\n";
exit(1);
}
if (argv[1] != "name" || argv[1] != "socsec") {
cerr << "Argument 1 must be either 'name' or 'socsec'.\n";
exit(1);
}
sortVar sortMode;
if (argv[1] == "name")
sortMode = NAME;
else if (argv[1] == "socsec")
sortMode = SOCSEC;
ifstream fin(argv[2]);
vector<record> nameList;
while(!fin.eof()) {
record r;
if (sortMode == NAME)
r.t_sort = false;
else if (sortMode == SOCSEC)
r.t_sort = true;
fin >> r;
nameList.push_back(r);
}
//sort(nameList.begin(), nameList.end());
//cout << nameList;
}
第一个问题:使用'='您要''==。你的编译器没有给你一个令人讨厌的警告吗? – 2012-02-17 22:56:05
通常,列出您正在使用的编译器以及获取的确切错误消息很有帮助。 – 2012-02-17 23:00:09
了解常量是否正确。没有必要将大多数参数作为非const的引用 – PlasmaHH 2012-02-17 23:16:31