2011-06-02 27 views
1

編輯:如何獲得的char []與性病::地圖工作回答後

<應提供std::map。有關最佳做法的更多信息,請參閱James McNellis的回答

此問題中包含的代碼寫得不好。這只是因爲我在玩SPOJ,輸入數據是嚴格有效的。 std::string方法是我最初選擇的方法,但結果不夠快。

謝謝。


我知道我不能地圖直接使用char[],如map<char[], int>。因此,我把它放在課堂上。但它仍然可以通過編譯。如何處理?


#include <stdio.h> 
#include <map> 

using namespace std; 

class id { 
public: 
    char v [30]; 
}; 

int main() { 
    map<id, int> m; 
    id a; 
    while (gets(a.v)) { 
     m[a]++; 
    } 
    return 0; 
} 

/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = id]’: 
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_map.h:418: instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = id, _Tp = int, _Compare = std::less<id>, _Alloc = std::allocator<std::pair<const id, int> >]’ 
prog.cpp:15: instantiated from here 
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’ 

看來它是與比較,但我仍然在黑暗中。

回答

3

您需要實現<操作

class id { 
public: 
    char v [30]; 
    bool operator<(const id &rhs) const{ 
     return strcmp(v,rhs.v) < 0; 
    } 
}; 

編輯:作爲一個方面說明你的代碼是一個做事的非常差的方式。看到一些解釋爲什麼的答案。

+0

你的回答正是我想要的。非常感謝你。 (有關代碼的問題在編輯問題中有解釋,我希望這是Stack Overflow的最佳工作方式,順便說一下,我的答案終於被接受了。) – 2011-06-02 04:34:44

6

首先要做的事:永遠不要使用gets。它不能安全使用,任何使用它的程序都有安全漏洞。無法限制gets可以寫入您提供的緩衝區的字符數,因此無法防止緩衝區溢出。如果您確實需要使用C I/O庫,則應該使用fgets,它允許您指定要讀取的最大字符數。

您看到此錯誤的原因是您使用的密鑰類型必須以某種方式具有可比性。默認情況下std::map使用operator<,您沒有爲id定義,因此編譯錯誤。您需要定義operator<來比較兩個對象,或者需要編寫一個可用於比較兩個對象的比較器函子。無論您選擇哪種,比較器都必須提供strict-weak ordering

既然你用C++編程,這裏的理想的解決方案是使用慣用的C++:

std::map<std::string, int> m; 
std::string s; 
while (std::cin >> s) { 
    m[s]++; 
} 

std::string已經提供operator<,提供了一個詞典式排序,所以你並不需要自己定義一個比較。

+0

+1爲C++方式 – GWW 2011-06-02 03:58:47

+0

'fgets'可以使用'的std :: cin'? – 2011-06-02 04:09:59

+0

不; 'fgets'是C標準庫的一部分,因此需要一個'FILE *',比如'stdin'。 – 2011-06-02 04:11:00

0

爲了插入地圖,地圖需要能夠比較ID的。您尚未提供可以使用的運營商<的實施。你有兩種選擇:

  1. 提供一個,這裏給出另一個答案的例子。
  2. 改爲使用std :: string。

我認爲你應該使用std :: string。您可以使用.c_str()方法在需要時將其轉換爲char數組。