2012-03-09 22 views
0

私はちょうどC++を起動しています(これは10年後のJAVAです)!私はStroupstrupの本の例に従っています。例外:STATUS_ACCESS_VIOLATION - ポインタを参照する

私は彼の本から次のコードセグメントをまとめています。

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

map<string, int>histogram; 
void record (const string &s) 
{ 
    histogram[s]++; //record frequency of "s" 
    cout<<"recorded:"<<s<<" occurence = "<<histogram[s]<<"\n"; 
} 

void print (const pair<const string, int>& r) 
{ 
    cout<<r.first<<' '<<r.second<<'\n'; 
} 

bool gt_42(const pair<const string, int>& r) 
{ 
    return r.second>42; 
} 

void f(map<string, int>& m) 
{ 
    typedef map<string, int>::const_iterator MI; 
    MI i = find_if(m.begin(), m.end(), gt_42); 
    cout<<i->first<<' '<<i->second; 
} 

int main() { 
    istream_iterator<string> ii(cin); 
    istream_iterator<string> eos; 
    cout<<"input end\n"; 

    for_each(ii, eos, record); 

    //typedef pair <string, int> String_Int_Pair; 
    //histogram.insert(String_Int_Pair("42", 1)); 
    //histogram.insert(String_Int_Pair("44", 1)); 


    //for_each(histogram.begin(), histogram.end(), print); 
    f(histogram); 

} 

私はエラーを取得 - 例外:STATUS_ACCESS_VIOLATIONを、私が参照I->まず、I->第二に考えて、私は推測します。問題が何であるかを誰かが助けてくれますか?また、役に立つC++フォーラムをいくつか提案することもできます。あなたのvoid f(map<string, int>& m)機能で

答えて

3

あなたが実際にあなたが、.egを探している要素見つかったかどうかをチェックしません:あなたはi->firstをaccesingているとき

void f(map<string, int>& m) 
{ 
    typedef map<string, int>::const_iterator MI; 
    MI i = find_if(m.begin(), m.end(), gt_42); 
    if(i != m.end()) 
     cout<<i->first<<' '<<i->second; 
    else 
     cout << "Not Found" << endl; 
} 

エラーはおそらくoccuresの際にエンド過去iポイントを」地図コンテナの

+0

申し訳ありませんが、r> second> 42を返すように注意を払っていませんでした。私はちょうどアルゴリズムを正しく読むのは不注意でした。申し訳ありません。ご回答いただきありがとうございます。 – Mahesh