今天给大家分享一个LHU算法

LHU就是历史记录算法

/*
* 实现:
*   1.最后输入最先出队
*   2.获取上一个下一个历史
*   3.加入一个新的历史
*   4.这个历史记录需要最大限制默认10
*/

/** 
* @file  	  history.h
* @author     李贵伟(409746848@qq.com)
* @date       2021-9-17
* @copyright  Copyright belong to Author.
* @see        --
* 
* 详细描述:
*/
#pragma once
/*
* 实现:
*   1.最后输入最先出队
*   2.获取上一个下一个历史
*   3.加入一个新的历史
*   4.这个历史记录需要最大限制默认10
*/

#include <vector>
#include <string>

using HISTORY_TYPE = std::vector<std::string>;

/**
 * @brief 支持默认拷贝构造
 *
 * 详细描述:
 */
class History
{
public:
    History();
    virtual ~History();
public:
    //最后输入最先出队
    std::string GetHistory();
    //获取上一个下一个历史
    void MovePre();
    void MoveNext();
    //加入一个新的历史
    void AddHistory(const std::string& record);
    //这个历史记录需要最大限制默认10
    void SetMaxLinite(int limite = 10);

public:
    inline int GetSize() { return (int)historys_.size(); }
protected:
    HISTORY_TYPE historys_;
    int cur_pos_;
    int limite_;
private:
};
#include "pch.h"
#include "history.h"


History::History():cur_pos_(0)
{
    SetMaxLinite();
}

History::~History()
{

}

std::string History::GetHistory()
{
    if (historys_.size() == 0) return "";
    if (cur_pos_ >= (int)historys_.size()) cur_pos_ = (int)historys_.size() - 1;
    if (cur_pos_ < 0) cur_pos_ = 0;

    return historys_[cur_pos_];
}

void History::MovePre()
{
    cur_pos_--;
}

void History::MoveNext()
{
    cur_pos_++;
}

void History::AddHistory(const std::string& record)
{
    historys_.emplace_back(record);

    if (historys_.size() > limite_)
    {
        historys_.erase(historys_.begin(), historys_.begin()+(historys_.size() - limite_));
    }
    cur_pos_ = (int)historys_.size()-1;
}

void History::SetMaxLinite(int limite /*= 10*/)
{
    limite_ = limite;
}

// LHU.cpp: 定义应用程序的入口点。
//

#include "LHU.h"
#include "history/history.h"

using namespace std;

int main()
{
	History h;
	std::string sLine;
	while (std::getline(std::cin, sLine))
	{
		if (sLine == "q")
		{
			break;
		}

		std::cout << sLine << std::endl;
		h.AddHistory(sLine);

		int sz = h.GetSize();
		std::cout << "history:" << "============================" << std::endl;

		while (sz-->0)
		{
            std::cout <<"\t"<< h.GetHistory() << std::endl;
			h.MovePre();
		}
	}
	cout << "Hello CMake." << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值