http://ica.openjudge.cn/struct/1/ 第一次用string類,踩的坑挺多,代碼改了一晚上還是嗎沒有AC。 主要兩點: 1.vector和string類里面的size和length函數返回值是size_type類型,是unsigned類型。因此s1.length()>s2.length()與s1.length()-s2.length()>0不等價,因為第二個式子為unsignded類型,恒為真。除此之外int j=s1.length()-s2.length()可以得到正確結果,因為強制轉換成int; 2.string中用data成員函數可以轉換成c中的字符數組形式的字符串。 3.bool類型除了0之外的值都是視作1,而非正數為1負數為0,重載>等比較運算符時尤其注意這一點。 4.第一次用了VS的單步調試。以及VS2013變得很智能,各種方便。鼠標放在某一個數據名上面自動顯示數據類型,如果早點知道就不會因為unsigned類型花費了一晚上。
說到底還是不知道為什么WA啊,真的真的花了整整一個晚上,不過學到的東西也挺多。為了下學期做準備。
代碼附上,紀念我的第一篇博客:
#include<iostream>#include<string>using namespace std;typedef struct{ string name; int m; int d; int sort_temp;}Stu;int Operator-(string s1, string s2){ for (int i = 0; i < s1.size() + 1; i++){ if (s1.data()[i] == s2.data()[i]) i++; else { return s1.data()[i] - s2.data()[i]; } return 0; }}bool operator>(string s1, string s2){ if (s1.length() == s2.length()){ if (s1 - s2 > 0)return true; else return false; } else if (s1.length() >s2.length())return true; /*else if ((s1.length() - s2.length()) > 0)return true; */ else return false;}bool operator>(Stu s1, Stu s2){ if (s1.sort_temp > s2.sort_temp) return true; else if (s1.sort_temp == s2.sort_temp) { if (s1.name > s2.name) return true; } return false;}int main(){ int n; cin >> n; if (n <= 0){ cout << "None" << endl; system("pause"); return 0; } /*string s1("Bill"), s2("Callf"); int j = s1.length() - s2.length(); cout << j;*/Stu *s=new Stu[n];for (int i = 0; i < n; i++){ cin >> s[i].name >> s[i].m >> s[i].d; s[i].sort_temp = s[i].m * 100 + s[i].d;}for (int i = 0; i < n; i++){ for (int j = 0; j < n - 1-i; j++){ if (s[j]>s[j + 1]) { Stu temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; } }}int i = 0;/*for (int i = 0; i < n; i++){ cout << s[i].name << " " << s[i].sort_temp<<endl;}*/bool flag = false;while(i<n){ if (s[i].sort_temp == s[i + 1].sort_temp){ flag = true; cout << s[i].m << " " << s[i].d << " " << s[i].name; while (s[i].sort_temp == s[i + 1].sort_temp){ i++; cout << " " << s[i].name; } cout << endl; } i++; }if (flag == false)cout << "None"<<endl;system("pause");return 0;}新聞熱點
疑難解答