我正在編寫一個程序,它將讀取帶有社會安全號碼(當然不是真正的)的名稱列表,並根據姓氏或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