【发布时间】:2012-03-09 08:16:01
【问题描述】:
我正在编写一个程序,它将读取带有社会安全号码(当然不是真实号码)的姓名列表,并根据命令行参数根据姓氏或 ssn 对列表进行排序。为了简单起见,我重载了
#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;
}
【问题讨论】:
-
第一个问题:在你想要
==的地方使用=。你的编译器没有给你一个讨厌的警告吗? -
一般来说,列出您正在使用的编译器以及您收到的确切错误消息会很有帮助。
-
了解 const 正确性。您的大多数参数都不需要引用非常量
-
您应该开始在代码中多使用
const...比较和插入运算符 (operator>>) 应该通过常量引用获取record参数(它们不应更改他们收到的对象)。
标签: c++ sorting stl operator-overloading stl-algorithm