2012-03-09 162 views
0

我刚刚启动了一些C++(即在JAVA 10年后!)。我正在学习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++论坛,这也会有所帮助。

回答

3

在你void f(map<string, int>& m)功能你不检查你是否真的发现你正在寻找,.eg元素:

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当你accesing i->firsti“过去的结束“地图容器的”“。

+0

对不起,我没有给予足够的重视返回r.second> 42时,意计数> 41,而不是INPUT否> 42。我只是不小心阅读正确的算法。对于那个很抱歉。感谢您的回复,sirgeorge。 – Mahesh 2012-03-09 17:51:20