2012-03-09 2 views
0

저는 C++ (10 년 동안의 JA! 이후)를 시작했습니다. 나는 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를 반환하는 데 충분한주의를 기울이지 않았습니다. count> 41이고 inputno.> 42가 아닌 경우 의미합니다. 방금 알고리즘을 제대로 읽지 못했습니다. 미안합니다. 답장을 보내 주셔서 감사합니다. – Mahesh

관련 문제