我想提出一个“更”现代的 C++ 和面向对象的解决方案。而且,一个完整的工作解决方案。
在 C++ 中,我们通常将数据和对这些数据进行操作的函数放入对象、类中。类并且只有类应该知道如何处理其数据。没有外部全局函数应该这样做。
因此,在您的示例中,“名称”和“分数”是对象的属性,从 std::istream 中提取它们或将它们插入到 std::ostream 中应该只有该对象知道并由它处理。
因此,我们创建了一个类/结构,定义了 2 个数据成员,即“名称”为std::string,“分数”为int。然后,我们覆盖提取器运算符 (>>) 和插入器运算符。提取器操作符有点棘手,因为我们首先读取完整的行,然后将其拆分为标记。
在 C++ 中,您的文件结构称为 CSV(逗号分隔值)。而且,阅读这是一项标准任务。首先,阅读完整的行,然后,使用给定的分隔符,提取该字符串的标记。 “拆分”也称为“标记化”,C++ 有专门的功能用于此目的:std::sregex_token_iterator。
这东西是一个迭代器。用于迭代字符串,因此是“sregex”。开始部分定义了我们将操作的输入范围,然后有一个 std::regex 用于在输入字符串中应该匹配/不应该匹配的内容。最后一个参数给出匹配策略的类型。
1 --> give me the stuff that I defined in the regex and
-1 --> give me that what is NOT matched based on the regex.
我们可以使用这个迭代器将标记存储在 std::vector 中。 std::vector 有一个范围构造函数,它接受 2 个迭代器作为参数,并将第一个迭代器和第二个迭代器之间的数据复制到 std::vector。声明
std::vector tokens(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});
将变量“tokens”定义为std::string 类型的std::vector,并使用std::vector 的所谓范围构造函数。请注意:我使用的是 C++17,可以在没有模板参数的情况下定义 std::vector。编译器可以从给定的函数参数中推断出参数。此功能称为 CTAD(“类模板参数推导”)。
此外,您可以看到我没有明确使用“end()”-iterator。
这个迭代器将从空的大括号括起来的初始值设定项列表中构造出来,并且具有正确的类型,因为std::vector 构造函数要求它与第一个参数的类型相同。
在读取该行并将其拆分为标记后,我们检查是否恰好有 2 个标记,然后将结果存储为“名称”和“分数”。所以,总的来说,这是一个非常简单的操作。
我们定义的下一个对象是 ScoreList。这包含上述定义对象的std::vector 作为数据成员和一些用于演示目的的附加成员函数。我们有一个
- 插入器过载
- 从文件加载
- 根据分数对列表进行排序
- 保存文件
- 添加新条目
只有前10名的秘诀是,对列表进行排序,只保存其中得分最高的10个名字。为此,我们使用std::algorithm std::copy_n。
为了读取完整的 csv-source-text 文件,我们还使用了专用功能。
首先,我们打开文件并检查是否正常。然后我们使用std::istream_iterator 从输入流中复制数据。这个迭代器,具有上述对象的给定类型,将逐行读取并将所有内容拆分为标记,并将结果插入我们内部std::vector 的后面。
std::copy(std::istream_iterator<NameAndScore>(is), {}, std::back_inserter(scoreList));
再次,非常简单和简短的单行。
其他功能也非常简单。不用再详细解释了。
在main 中,我添加了一些驱动程序代码来向您展示它的外观。当然,您可以简单地添加任何其他功能,无论您需要什么。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <regex>
#include <algorithm>
const std::string delimiter("|");
const std::regex re("\\" + delimiter);
struct NameAndScore {
// The data
std::string name{};
int score{};
// Member functions
// Overwrite extractor operator
friend std::istream& operator >> (std::istream& is, NameAndScore& ns) {
// Read a comlete line
if (std::string line; std::getline(is, line)) {
// Split it into parts
std::vector tokens(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});
// If we have 2 parts, then assign to our internal data
if (2 == tokens.size()) {
ns.name = tokens[0];
ns.score = std::stoi(tokens[1]);
}
}
return is;
}
// Overwrite inserter operator
friend std::ostream& operator << (std::ostream& os, const NameAndScore& ns) {
return os << ns.name << " " << delimiter << " " << ns.score;
}
};
class ScoreList {
static constexpr size_t MaxElementsInList = 10;
std::vector<NameAndScore> scoreList{};
public:
// Inserter operator
friend std::ostream& operator << (std::ostream& os, const ScoreList& sl) {
std::for_each(sl.scoreList.begin(), sl.scoreList.end(), [&os](const NameAndScore& ns) {os << ns << "\n";});
return os;
}
// Read score list from disk
void load(const std::string& filename) {
// Clear existing score list
scoreList.clear();
// Open file and check if OK
if (std::ifstream is(filename); is) {
// Read all data from file
std::copy(std::istream_iterator<NameAndScore>(is), {}, std::back_inserter(scoreList));
}
}
// Write Scorelist to disk
void save(const std::string& filename) {
// Open file and check, if it is OK
if (std::ofstream os(filename); os) {
sort();
// Write 10 entries to a file
std::copy_n(scoreList.begin(), MaxElementsInList, std::ostream_iterator<NameAndScore>(os, "\n"));
}
}
// Sort the score list
void sort() {
std::sort(scoreList.begin(), scoreList.end(), [](const NameAndScore & s1, const NameAndScore & s2) { return s2.score < s1.score; });
}
// Add a new enty from the user
void addEntry() {
std::cout << "\nPlease enter your name: ";
if (std::string name; std::cin >> name) {
std::cout << "\nPlease enter your score: ";
if (int score; std::cin >> score)
scoreList.emplace_back(NameAndScore({name, score }));
}
}
};
const std::string filenameScoreList("r:\\Scores.txt");
int main() {
// Define an empty score list
ScoreList sl{};
// Load contents from file
sl.load(filenameScoreList);
// Show contents
std::cout << sl;
// Add a new entry, given by the user
sl.addEntry();
// Sort and save 10 top most scored data in a file
sl.save(filenameScoreList);
// Jsut for demo purposes. Load the file again
// And sho the result
sl.load(filenameScoreList);
std::cout << sl;
return 0;
}
我希望,我能给你一个想法,你的问题是如何解决的。 . .