【问题标题】:Exception: STATUS_ACCESS_VIOLATION - pointer referencing例外:STATUS_ACCESS_VIOLATION - 指针引用
【发布时间】:2012-03-09 05:46:36
【问题描述】:

我刚刚开始使用 C++(那是在 10 年的 JAVA 之后!)。我正在遵循 Stroupstrup 书中的示例。

我将他书中的以下代码段放在一起。

#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->first,i->second,我猜。有人可以帮我找出问题所在。另外,如果您能推荐一些其他的 C++ 论坛,它们也会有所帮助。

【问题讨论】:

    标签: c++ pointers exception


    【解决方案1】:

    在您的 void f(map&lt;string, int&gt;&amp; m) 函数中,您不会检查是否确实找到了您正在寻找的元素,例如:

    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;
    }
    

    i 指向地图容器的“结束” 时,您访问i-&gt;first 时可能会发生错误。

    【讨论】:

    • 对不起,我没有足够注意返回 r.second>42,这意味着当 count>41 而不是 inputno.>42 时。我只是粗心地正确阅读了算法。对于那个很抱歉。谢谢你的回复,sirgeorge。
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    相关资源
    最近更新 更多