2013-04-16 80 views
2

我想做一個小的哈希程序,但有一個錯誤,我不知道如何處理。問題是上的箭頭,這裏是錯誤:迭代器錯誤C2440

Error 1 error C2440: 'initializing' : cannot convert from 'std::_String_const_iterator<_Elem,_Traits,_Alloc>' to 'std::_String_iterator<_Elem,_Traits,_Alloc>'

我的代碼:

#include <iostream> 
#include <string> 
#include <iterator> 
using namespace std; 

unsigned long hash(const string& str); 

int main() 
{ 
    long out; 
    string word; 
    word = "about"; 
    out = hash(word) % 255; 
    cout << out; 
    system("pause"); 
    return 0; 
} 


unsigned long djb2(const string& str) 
{ 
    unsigned long hash = 5381; 

    for(string::iterator it=str.begin();it!=str.end();it++) //<~~~~~~~~~~ 
     hash = ((hash << 5) + hash) + *it; /* hash * 33 + character */ 

    return hash; 
} 
+0

無法將** _ St​​ring_const_iterator **轉換爲** _ St​​ring_iterator **。確保你徹底閱讀你的錯誤信息,他們是你的朋友! – Aesthete

+0

沒有定義'unsigned long hash(const string & str);'。最重要的是,你已經命名了你的函數和變量是相同的,這並不是很好,我認爲'djb2()'函數應該是是'hash()'? – Aesthete

回答

5

您需要使用const_iterator

for(std::string::const_iterator it=str.begin();it!=str.end();it++) 

因爲你的函數參數是const string &striterator必須同意。

+0

我用const_iterator替換了interator,現在出現了2個錯誤1:錯誤錯誤LNK2019:無法解析的外部符號「unsigned long __cdecl hash(class std :: basic_string ,class std :: allocator > const&)「(?hash @@ YAKABV?$ basic_string @ DU?$ char_traits @ D @ std @@ V?$ allocator @ D @ 2 @@ std @@@ Z)引用函數_main \t hashtest1.obj \t hashtest1和2:錯誤致命錯誤LNK1120:1無法解析的外部\t C:\ Users \ Manos \ Docum ents \ Visual Studio 2008 \ Projects \ hashtest1 \ Debug \ hashtest1.exe \t hashtest1 –

+0

我很抱歉...我的心太麻痹了。並感謝你:) –

+0

@ user2145433 Esthete是正確的,你沒有定義函數'哈希',你通常應該避免使用相同的名稱。 –