代码拉取完成,页面将自动刷新
#pragma once
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
#include <fstream>
#include <cassert>
#include <cstdlib>
#include "../comm/log.hpp"
#include "../comm/util.hpp"
// 文件版本,从文件中读取题目信息
namespace ns_model
{
using namespace ns_log;
using namespace ns_util;
// 题目信息
// 清单格式:1 判断回文数 1 1 1000
struct Question
{
std::string number; // 题号
std::string title; // 题目
std::string star; // 难度
int cpu_limit; // 时间限制
int mem_limit; // 空间限制
std::string desc; // 题目描述
std::string header; // 提前预设的代码(用户未提交)
std::string tail; // 测试用例
};
const std::string questions_path = "./questions/"; // 题库所在文件夹
const std::string questions_list = "./questions/questions.list"; // 题库清单的路径
class Model
{
private:
// 题号->题目信息 的映射关系
std::unordered_map<std::string, Question> questions;
public:
Model()
{
assert(LoadAllQuestions(questions_list));
}
~Model()
{
}
// 从清单中加载题目信息到哈希表中
bool LoadAllQuestions(const std::string &question_list)
{
std::ifstream in(question_list); // 打开流
if (!in.is_open()) // 打开失败
{
LOG(FATAL) << " 加载题目列表失败,请检查是否存在题库文件 " << "\n";
return false;
}
// 打开成功,开始读文件
std::string line;
// 按行读
while (getline(in, line))
{
std::vector<std::string> token;
// 切割读到的字符串,并把字段插入到哈希表中
// 1. 切割 line,把切割后的字段放入数组 token 中
StringUtil::SplitString(line, &token, " ");
// 2.把字段放入哈希表中
// 1 判断回文数 1 1 1000
if (token.size() != 5)
{
LOG(WARNING) << " 部分题目格式错误,加载失败,请检查文件格式 " << "\n";
continue;
}
// 填写结构体
Question q;
q.number = token[0];
q.title = token[1];
q.star = token[2];
q.cpu_limit = std::stoi(token[3]);
q.mem_limit = std::stoi(token[4]);
// 格式:./questions/1/
std::string path = questions_path;
path += q.number;
path += "/";
FileUtil::ReadFile(path + "desc.txt", &(q.desc), true);
FileUtil::ReadFile(path + "header.cpp", &(q.header), true);
FileUtil::ReadFile(path + "tail.cpp", &(q.tail), true);
questions.insert({q.number, q});
}
LOG(INFO) << " 加载题库成功 " << "\n";
in.close();
}
// 获取整个题库,out是输出型参数
bool GetAllQuestions(std::vector<Question> *out)
{
if (questions.empty())
{
LOG(ERROR) << " 用户获取题库失败 " << "\n";
return false;
}
for (const auto &q : questions)
{
out->push_back(q.second);
}
return true;
}
// 获取指定题目,number为题号,out是输出型参数
bool GetOneQuestion(const std::string &number, Question *out)
{
const auto &iter = questions.find(number);
if (iter == questions.end())
{
LOG(ERROR) << "题目获取失败,题目编号:" << number << "\n";
return false;
}
*out = iter->second;
return true;
}
};
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。