原创 一个hash_map使用错误收藏


一个hash_map使用错误

g++的 hash_map 运行不起来

#include <string>
#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;

namespace __gnu_cxx
{
        template<> struct hash<const string>
        {
                size_t operator()(const string& s) const
                { return hash()(s.c_str()); }
        };
        template<> struct hash<string>
        {
                size_t operator()(const string& s) const
                { return hash()(s.c_str()); }
        };
}

int main( void )
{
        hash_map<string,int> a;
        a["abc"] = 1; // 这一句一执行的话,程序直接退出

        system("pause");
}

该段代码由 周星星 贴于 http://blog.vckbase.com/jzhang/archive/2006/03/28/18807.html

试运行,确实会崩溃。
经debug跟踪,很快就能找到错误来源。

原来是
template<> struct hash<string>::operator()(const string &)
定义成了无穷递归。

如下修正:

        template<> struct hash<string>
        {
                size_t operator()(const string& s) const
                {
                        return __stl_hash_string(s.c_str());
                }
        };

 

发表于 @ 2006年07月20日 16:44:00|评论(loading...)

新一篇: 最简单的一个wxPython窗口 | 旧一篇: 纠错一个Python程序引发的讨论

用户操作
[即时聊天] [发私信] [加为好友]
金庆
订阅我的博客
XML聚合  FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
金庆的公告
XSTL封面 Locations of visitors to this page Codeguru Contributor
订阅 上海程序员
文章分类
收藏
    热门文章
    1 评“程序员怎么样才能保证自己的程序没有BUG”
    2 C语言HTML解析器ekhtml的VC编译
    3 log4cpp应用速成手册
    4 一个hash_map使用错误
    5 udp广播与直接广播
    6 评“加班文化”对软件企业的危害
    作者推荐
    1 设计死了吗?
    2 葵花宝典:软件开发高手是这样炼成的!
    3 TCP截包分段重组的设计
    4 Firefox的HTTP内容解压代码阅读
    5 不可思议:using namespace无效!
    6 作业调度问题深度搜索定界算法
    7 智能机器人编程游戏robocode的运行代码简析
    存档
    Csdn Blog version 3.1a
    Copyright © 金庆