步骤
- 创建一个JSON配置文件:例如
config.json
。 - 在C++代码中读取并解析该配置文件。
- 根据配置文件内容执行相应的操作。
示例
1. 创建config.json
配置文件
{
"threshold": 10
}
这个配置文件定义了一个阈值 threshold
,用于决定在排序时选择哪个算法。
2. 安装nlohmann/json
库
你可以通过以下命令安装该库:
# 使用vcpkg安装
vcpkg install nlohmann-json
# 使用CMake FetchContent
# 将以下内容添加到CMakeLists.txt中
FetchContent_Declare(
nlohmann_json
GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.10.5
)
FetchContent_MakeAvailable(nlohmann_json)
3. 在C++代码中使用配置文件
#include <iostream>
#include <vector>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// 插入排序
void insertionSort(std::vector<int>& arr) {
int n = arr.size();
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// 快速排序的分区函数
int partition(std::vector<int>& arr, int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]);
return (i + 1);
}
// 快速排序
void quickSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// 主排序函数,根据配置选择不同的排序算法
void sortArray(std::vector<int>& arr, int threshold) {
int n = arr.size();
if (n <= threshold) {
insertionSort(arr);
} else {
quickSort(arr, 0, n - 1);
}
}
// 从JSON文件读取配置
int getConfigValue(const std::string& configPath) {
std::ifstream configFile(configPath);
json config;
configFile >> config;
return config["threshold"];
}
// 测试函数
void printArray(const std::vector<int>& arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}
int main() {
std::vector<int> arr = {12, 11, 13, 5, 6, 7};
std::cout << "排序前的数组: ";
printArray(arr);
// 从配置文件获取阈值
int threshold = getConfigValue("config.json");
sortArray(arr, threshold);
std::cout << "排序后的数组: ";
printArray(arr);
return 0;
}
代码说明
- 配置文件
config.json
:在外部定义了排序算法的阈值。 getConfigValue
函数:从配置文件中读取threshold
的值。nlohmann/json
库:用于解析JSON配置文件。sortArray
函数:根据读取到的阈值决定使用插入排序或快速排序。
运行程序
运行这个C++程序时,它会读取config.json
中的阈值并根据该值执行排序算法。通过修改config.json
文件中的threshold
值,你可以在无需重新编译代码的情况下调整程序的行为。