/****************************Assoc.h**************************************/

#if !defined(AFX_ASSOC_H__FBB8B380_5C3D_4A4D_A497_B45C77B2BDAE__INCLUDED_)
#define AFX_ASSOC_H__FBB8B380_5C3D_4A4D_A497_B45C77B2BDAE__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

typedef struct trgPair
{
    char *name;     //
放字符串
    int val;        //
统计这种字符串的个数
}STUPAIR, *PSUTPAIR;

class CAssoc
{
private:
    STUPAIR *m_pstuPair;    //
结构体指针,构造函数时初始化数量
    int m_nMax;             //new
到了多少个结构体
    int m_nFree;            //
已经使用了多少个
    friend class CAssoc_iterator;
public:
    //
带参构造,new多少个结体体出来
    CAssoc(int nLen);
    // []
重载
    int &operator[](const char *pszBuf);
    void print_all();
};

#endif // !defined(AFX_ASSOC_H__FBB8B380_5C3D_4A4D_A497_B45C77B2BDAE__INCLUDED_)

 

/***************************Assoc.cpp*************************************/
#include "stdafx.h"
#include <string.h>
#include <iostream.h>
#include "Assoc.h"

CAssoc::CAssoc(int nLen)
{
    m_nMax = nLen;
    m_nFree = 0;
    m_pstuPair=new STUPAIR[nLen];
}

int &CAssoc::operator[](const char *pszBuf)
{
    //
一个昨时结构体指针
    STUPAIR *pstuPair;
    //
这里有一个很巧妙的地方.m_Free这个偏移刚好指向没使用过的空间
    //
所以-1,刚好就能得到最后一次使用的空间偏移
    //
第一次0-1,刚好就不会满足中间的循环条件也就不会进入循环了.
    //pstuPair--
也就是-地址,直接条件不滞退出循环

    for(pstuPair = &m_pstuPair[m_nFree-1]; m_pstuPair <= pstuPair; pstuPair--)
    {
        if(0 == strcmp(pszBuf, pstuPair->name))
        {
            //
依次遍历已经有的字符串,找到符合的话,直接返回计数引用
            return pstuPair->val;
        }
    }
    //
指针的给值后,使用空间加1
    pstuPair = &m_pstuPair[m_nFree++];
    //
把字符串放进来
    pstuPair->name = new char[strlen(pszBuf)+1];
    strcpy(pstuPair->name, pszBuf);
    //
该字符串次数先设为0
    pstuPair->val = 0;
    //
返回记次的引用,返回后,马上就+1
    return pstuPair->val;
}

void CAssoc::print_all()
{
    for(int i = 0; i < m_nFree; i++)
    {
        cout << m_pstuPair[i].name << ":" << m_pstuPair[i].val << endl;
    }
}

 

 

/*运算符重载简单应用--统计输入同样字符串的次数*/

#include "stdafx.h"
#include <iostream.h>
#include <string.h>
#include "Assoc.h"

void main( )
{
    char szbuf[256];
   
    CAssoc theAssoc(5);
   
    while( cin>>szbuf )
    {
        if ( strcmp(szbuf , "0") == 0 )
        {
            break;
        }
        theAssoc[szbuf]++;
    }
    theAssoc.print_all();
}

posted on 2010-02-04 21:24  o无尘o  阅读(260)  评论(0编辑  收藏  举报