#include <iostream> #include <fstream> #include<string> #include "nlohmann/json.hpp" using json = nlohmann::json; // 定义链表节点 struct Node { int comment; std::string from; std::vector<std::string> comments; std::string to; float score; std::string corp; std::string time; Node* next; }; void readJsonToLinkedList(std::string filename, Node*& head) { std::ifstream infile(filename); json j; infile >> j; for (auto& element : j) { Node* newNode = new Node(); newNode->comment = element["comment"]; newNode->from = element["from"]; newNode->comments = element["comments"]; newNode->to = element["to"]; newNode->score = std::stof(element["score"].get<std::string>()); newNode->corp = element["corp"]; newNode->time = element["time"]; // 插入节点到链表尾部 if (head == nullptr) { head = newNode; } else { Node* current = head; while (current->next != nullptr) { current = current->next; } current->next = newNode; } } } //从链表中进行筛选的函数 void saveRecords(Node* head, float lowerBound, float upperBound) { std::ofstream outfile("results.dat"); Node* current = head; while (current != nullptr) { if (current->score >= lowerBound && current->score <= upperBound) { outfile << current->from << "," << current->to << "," << current->score << std::endl; } current = current->next; } outfile.close(); } int main() { Node* head = nullptr; readJsonToLinkedList("C:\\Users\\86130\\source\\repos\\数据结构课程设计\\rating.json", head); // 从用户输入中获取评分范围 float low, high; std::cout << "请输入评分下界: "; std::cin >> low; std::cout << "请输入评分上界:"; std::cin >> high; saveRecords(head, low, high); return 0; }对于该代码是如何进行数据处理的
时间: 2024-03-07 16:51:03 浏览: 89
该代码是一个 C++ 程序,它通过读取一个 JSON 格式的文件并将其转换为链表的形式,然后根据用户输入的评分范围筛选链表中的节点数据,并将结果保存到一个名为 "results.dat" 的文件中。
具体来说,该程序首先定义了一个链表节点 Node,其中包含了评分(comment)、评分者(from)、被评分者(to)、评论(comments)、评分时间(time)、评分公司(corp)和得分(score)七个属性,以及一个指向下一个节点的指针 next。
然后,程序定义了一个函数 readJsonToLinkedList,用于将 JSON 文件中的数据读入到链表中。该函数首先打开指定的文件,然后使用 nlohmann/json 库对文件内容进行解析,解析后的数据存储在一个名为 j 的变量中。接着,程序遍历 j 中的每一个元素,即每一条评分记录,为它创建一个新的链表节点,并将该节点插入到链表的尾部。
最后,程序定义了一个名为 saveRecords 的函数,用于从链表中筛选出评分在指定范围内的节点,并将它们的评分者、被评分者和得分保存到一个名为 "results.dat" 的文件中。
在 main 函数中,程序首先定义了一个头指针 head,并将其初始化为 nullptr。然后,程序调用 readJsonToLinkedList 函数,将指定的 JSON 文件读入到链表中。接着,程序提示用户输入评分范围,然后调用 saveRecords 函数,将符合条件的节点数据保存到文件中。最后,程序返回 0,表示程序正常结束。
相关问题
分析下面代码并完善用c++语言编程利用双链表 (doubly-linked list)来模拟一列可正可逆 “时空列车”。每节车厢既能向前也 能向后行驶,且允许在时空节点处“分裂”“翻转”“重组”。项目要求在命令行下完成一整套 分类,在车头插入车厢,遍历功能。#include <iostream> #include <string> #include <fstream> #include <vector> #include <algorithm> #include “nlohmann/json.hpp” using json = nlohmann::json; // Define alias for json for convenience using namespace std; // Use standard namespace /******************************************************************* Car struct definition *******************************************************************/ struct Car { int id; // Car ID (unique identifier) string type; // Car type (e.g., passenger, freight, dining) double weight; // Car weight (tons) double length; // Car length (meters) string timestamp; // Timestamp (creation/last modified)
以下是对您提供的代码片段的分析和补充。我们将使用C++语言,基于双链表(doubly-linked list)实现一个“时空列车”模拟系统,支持车头插入车厢、遍历功能以及“分裂”、“翻转”、“重组”等操作。
---
### 分析与完善
#### 1. **现有代码结构**
- 您提供了一个`Car`结构体,用于表示每节车厢的基本属性。
- 缺少双链表的定义和相关操作函数。
- 需要实现的功能包括:
- 在车头插入车厢。
- 遍历列车的所有车厢。
- 支持“分裂”、“翻转”、“重组”等操作。
#### 2. **改进方案**
我们将设计一个`DoublyLinkedList`类来管理列车车厢,并在其中实现所需的操作。以下是完整的代码实现:
---
### 完整代码实现
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// Car struct definition
struct Car {
int id; // Car ID (unique identifier)
string type; // Car type (e.g., passenger, freight, dining)
double weight; // Car weight (tons)
double length; // Car length (meters)
string timestamp; // Timestamp (creation/last modified)
// Constructor for Car
Car(int id, string type, double weight, double length, string timestamp)
: id(id), type(type), weight(weight), length(length), timestamp(timestamp) {}
void display() const {
cout << "ID: " << id << ", Type: " << type
<< ", Weight: " << weight << " tons, Length: " << length << " meters"
<< ", Timestamp: " << timestamp << endl;
}
};
// Doubly Linked List Node Definition
struct Node {
Car car; // Data part
Node* prev; // Pointer to previous node
Node* next; // Pointer to next node
// Constructor for Node
Node(Car car) : car(car), prev(nullptr), next(nullptr) {}
};
// Doubly Linked List Class Definition
class DoublyLinkedList {
private:
Node* head; // Head of the list
Node* tail; // Tail of the list
public:
// Constructor
DoublyLinkedList() : head(nullptr), tail(nullptr) {}
// Destructor
~DoublyLinkedList() {
clear();
}
// Insert a new car at the head of the train
void insertAtHead(Car car) {
Node* newNode = new Node(car);
if (!head) {
head = tail = newNode;
} else {
newNode->next = head;
head->prev = newNode;
head = newNode;
}
}
// Traverse and display all cars in the train
void traverseForward() const {
Node* current = head;
cout << "Traversing Forward:" << endl;
while (current) {
current->car.display();
current = current->next;
}
}
void traverseBackward() const {
Node* current = tail;
cout << "Traversing Backward:" << endl;
while (current) {
current->car.display();
current = current->prev;
}
}
// Split the train into two parts at a given car ID
pair<DoublyLinkedList, DoublyLinkedList> split(int id) {
DoublyLinkedList firstPart, secondPart;
Node* current = head;
bool found = false;
while (current) {
if (current->car.id == id) {
found = true;
break;
}
firstPart.insertAtHead(current->car);
current = current->next;
}
if (found) {
current = current->next;
while (current) {
secondPart.insertAtHead(current->car);
current = current->next;
}
}
return {firstPart, secondPart};
}
// Reverse the entire train
void reverse() {
Node* temp = nullptr;
Node* current = head;
while (current) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
if (temp) {
head = temp->prev;
}
}
// Clear the entire train
void clear() {
Node* current = head;
while (current) {
Node* nextNode = current->next;
delete current;
current = nextNode;
}
head = tail = nullptr;
}
};
int main() {
DoublyLinkedList train;
// Insert some cars at the head
train.insertAtHead(Car(1, "Passenger", 30.5, 25.0, "2023-10-01 12:00"));
train.insertAtHead(Car(2, "Freight", 50.0, 30.0, "2023-10-01 12:05"));
train.insertAtHead(Car(3, "Dining", 20.0, 20.0, "2023-10-01 12:10"));
// Traverse forward
train.traverseForward();
// Traverse backward
train.traverseBackward();
// Split the train at car with ID 2
auto [firstTrain, secondTrain] = train.split(2);
cout << "First Train After Split:" << endl;
firstTrain.traverseForward();
cout << "Second Train After Split:" << endl;
secondTrain.traverseForward();
// Reverse the first train
firstTrain.reverse();
cout << "First Train After Reversal:" << endl;
firstTrain.traverseForward();
return 0;
}
```
---
### 解释
1. **`Car`结构体**:
- 表示每节车厢的基本信息,包括ID、类型、重量、长度和时间戳。
- 提供了构造函数和`display`方法用于输出车厢信息。
2. **`Node`结构体**:
- 双链表的节点,包含指向前后节点的指针和存储的车厢数据。
3. **`DoublyLinkedList`类**:
- 实现了双链表的基本操作,包括:
- `insertAtHead`:在车头插入车厢。
- `traverseForward` 和 `traverseBackward`:分别从前到后和从后到前遍历列车。
- `split`:根据指定车厢ID将列车分割为两部分。
- `reverse`:翻转整个列车。
- `clear`:释放所有节点内存。
4. **主函数**:
- 创建列车并插入几节车厢。
- 遍历列车并展示车厢信息。
- 测试列车的分裂、翻转等功能。
---
###
nlohmann::json 存储数据
### 如何使用 `nlohmann` 库进行 C++ 数据存储
#### 创建 JSON 对象并添加数据
可以创建一个 `json` 类型的对象来表示 JSON 数据结构。通过键值对的方式向该对象中添加数据。
```cpp
#include <iostream>
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
int main() {
// 创建JSON对象
json j;
// 添加基本类型的键值对
j["pi"] = 3.141; // 浮点数
j["happy"] = true; // 布尔值
// 复杂的数据类型也可以被轻松处理
j["nested_object"]["key_within_nested_obj"] = "value"; // 嵌套对象
j["my_array"] = {1, 2, 3, 4}; // 数组
}
```
#### 将复杂的数据结构转换成 JSON 字符串
一旦有了填充好的 JSON 对象,就可以很容易地将其序列化为字符串形式以便于保存到文件或其他持久化介质上。
```cpp
// 转换为字符串
std::string s = j.dump(); // 默认缩进级别为0 (紧凑模式)
std::cout << "Compact JSON string:\n" << s << '\n';
// 或者带有格式化的输出(指定缩进宽度)
s = j.dump(4); // 缩进四个空格
std::cout << "\nFormatted JSON string with indent=4:\n" << s << '\n';
```
#### 存储至文件
为了长期保持这些信息,通常会把生成的 JSON 文本写入磁盘上的某个位置。
```cpp
// 打开/创建文件流准备写入
std::ofstream o("example.json");
if (!o.is_open()) throw std::runtime_error("Failed to open file");
// 向文件写出已格式化的JSON内容
o << j.dump(4);
// 关闭文件流
o.close();
```
上述过程展示了如何利用 `nlohmann/json` 来构建 JSON 表达式,并最终将它们存入外部资源中[^1]。
阅读全文
相关推荐
















