2011-07-13 53 views
6

我在做項目歐拉#22:編譯器給了項目歐拉#不同的答案22

使用names.txt中(右鍵「目標另存/目標爲...」),一個46K的文本包含五千多個名字的 文件,首先按照字母順序排列 。然後計算每個名稱的 的字母值,將該值乘以其在 列表中的字母位置以獲得名稱分數。

例如,當列表按字母順序排序時,值爲3 + 15 + 12 + 9 + 14 = 53的COLIN 是 列表中的第938個名稱。因此,COLIN將獲得938×53 = 49714的分數。

文件中所有名稱得分的總和是多少?

用Cygwin的gcc-g ++編譯器編譯我的代碼,答案是871129635。但對於Visual Studio 2008,答案是正確的,871198282。爲什麼會這樣?

#include<iostream> 
#include<fstream> 
#include<vector> 
#include<algorithm> 
using namespace std; 

bool strCmp(string x, string y) { 
    if(x.compare(y) == -1) 
     return true; 
    else 
     return false; 
} 

int getScore(string s) { 
    int score = 0; 
    for(unsigned int i = 0; i < s.length(); i++) 
     score += (((int) s.at(i)) - 64); 
    return score; 
} 

int getTotalScore(vector<string> names) { 
    int total = 0; 
    for(unsigned int i = 0; i < names.size(); i++) 
     total += (getScore(names[i]) * (i+1)); 
    return total; 
} 

int main() { 
    vector<string> names; 
    ifstream namesFile("names.txt"); 

    char curChar; 
    string curName = ""; 

    //get names from file 
    if(namesFile.is_open()) { 
     while(!namesFile.eof()) { 
      curChar = namesFile.get(); 

      if(isalpha(curChar)) 
       curName.push_back(curChar); 
      else { 
       if(!curName.empty()) {//store finished name 
        names.push_back(curName); 
        curName.clear(); 
       } 
      } 
     } 
    } 
    namesFile.close(); 

    //alphabetize 
    sort(names.begin(), names.end(), strCmp); 

    //count up name scores 
    cout << getTotalScore(names) << endl; 
    return 0; 
} 
+2

在你的strCmp函數中,爲什麼要將比較函數的結果與-1進行比較?沒有承諾比較會返回一個特定的數字,只是如果'lhs

回答

9

這裏:

if(x.compare(y) == -1) 

你假設std::string::compare將返回-1爲低於的結果,但它其實是可以返回任何負值。您可以通過使用x.compare(y) < 0來解決此問題,但最好只寫x<y。實際上,您甚至不需要strCmp函數,因爲std::sort的默認行爲是使用operator<來比較元素。