我有以下以pair作为键的映射用法,并且它出现段错误。 有任何想法吗?

发布于 2024-07-27 13:56:00 字数 1149 浏览 0 评论 0原文

我简化了示例以帮助提高可靠性。 错误如下代码:

    #include <map>
    #include<iostream>
    #include<string>

    using namespace std;



    class A
    {

    public:
        map<pair<string, string>, string* > m;
        string str;

        A():str("sdfsd")
        {
            m[make_pair("aa","bb")]=&str;

        }   
        void foo()
        {
            map<pair<string, string>, string*>::iterator iter =m.begin();
            cout<<"In A::foo:\n";
            for(; iter!=m.end(); iter++)
            {
                pair<string, string> keys=iter->first;
                cout<<"map and test = "<<str<<" and "<<*iter->second<<endl;
            }
        } 
    };

    int main()
    {
    A a;
    a.foo();
    }

在核心文件中:

 #0  0x0066f6c7 in std::string::_Rep::_M_grab () from
 /usr/lib/libstdc++.so.5
 #1  0x0066f80c in std::basic_string,
 std::allocator >::basic_string
 () from /usr/lib/libstdc++.so.5
 #2  0x087e1e69 in pair (this=0xbfff7070,
 _ctor_arg=@0x9c087d0) at (pair keys=iter->first;)

I simpled the example to help with reability. Error follows the code:

    #include <map>
    #include<iostream>
    #include<string>

    using namespace std;



    class A
    {

    public:
        map<pair<string, string>, string* > m;
        string str;

        A():str("sdfsd")
        {
            m[make_pair("aa","bb")]=&str;

        }   
        void foo()
        {
            map<pair<string, string>, string*>::iterator iter =m.begin();
            cout<<"In A::foo:\n";
            for(; iter!=m.end(); iter++)
            {
                pair<string, string> keys=iter->first;
                cout<<"map and test = "<<str<<" and "<<*iter->second<<endl;
            }
        } 
    };

    int main()
    {
    A a;
    a.foo();
    }

In core file:

 #0  0x0066f6c7 in std::string::_Rep::_M_grab () from
 /usr/lib/libstdc++.so.5
 #1  0x0066f80c in std::basic_string,
 std::allocator >::basic_string
 () from /usr/lib/libstdc++.so.5
 #2  0x087e1e69 in pair (this=0xbfff7070,
 _ctor_arg=@0x9c087d0) at (pair keys=iter->first;)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红ご颜醉 2024-08-03 13:56:00

是编译器的问题吗? 它看起来像是一些奇怪的编译器优化,特别是当别名 iter->first 产生差异时。

刚刚发布到在线编译器 http://codepad.org/ZhYvtj9v
它给出了正确的结果,没有段错误。

Is it a compiler problem? It looks like some weird compiler optimisation, especially when aliasing iter->first makes the difference.

Just posted onto online compiler at http://codepad.org/ZhYvtj9v
and it gave the correct result, without segfault.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文