C++开发中config的配置和使用

步骤

  1. 创建一个JSON配置文件:例如 config.json
  2. 在C++代码中读取并解析该配置文件
  3. 根据配置文件内容执行相应的操作

示例

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;
}

代码说明

  1. 配置文件config.json:在外部定义了排序算法的阈值。
  2. getConfigValue函数:从配置文件中读取threshold的值。
  3. nlohmann/json:用于解析JSON配置文件。
  4. sortArray函数:根据读取到的阈值决定使用插入排序或快速排序。

运行程序

运行这个C++程序时,它会读取config.json中的阈值并根据该值执行排序算法。通过修改config.json文件中的threshold值,你可以在无需重新编译代码的情况下调整程序的行为。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值