C++ 数组声明错误:使用变量定义数组大小的解决方法

在 C++ 中,声明数组时不能使用变量来定义数组的大小,因为数组大小必须在编译时确定。以下代码示例展示了常见的错误:

// 统计正例和负例的数量
int num_positives = 0;
int num_negatives = 0;
for (int i = 0; i < num_samples; i++) {
    if (labels[i] == 1) {
        num_positives++;
    }
    else {
        num_negatives++;
    }
}

// 计算TPR和FPR
double tpr[num_positives + 1];
double fpr[num_negatives + 1];

**错误原因:**在声明数组 tprfpr 时,数组的大小不能使用变量 num_positivesnum_negatives 来定义,因为它们的值是在运行时确定的,而数组的大小必须在编译时确定。

解决方法:

1. 使用动态数组:

// 统计正例和负例的数量
int num_positives = 0;
int num_negatives = 0;
for (int i = 0; i < num_samples; i++) {
    if (labels[i] == 1) {
        num_positives++;
    }
    else {
        num_negatives++;
    }
}

// 计算TPR和FPR
double* tpr = new double[num_positives + 1];
double* fpr = new double[num_negatives + 1];

// 使用动态数组进行计算和操作

// 最后记得释放动态数组的内存
delete[] tpr;
delete[] fpr;

2. 使用固定大小的数组:

// 假设正例和负例的最大数量分别为 max_positives 和 max_negatives
const int max_positives = 100;
const int max_negatives = 100;

// 统计正例和负例的数量
int num_positives = 0;
int num_negatives = 0;
for (int i = 0; i < num_samples; i++) {
    if (labels[i] == 1) {
        num_positives++;
    }
    else {
        num_negatives++;
    }
}

// 检查数量是否超过最大值
if (num_positives > max_positives || num_negatives > max_negatives) {
    // 数量超过最大值,需要进行处理
}

// 计算TPR和FPR
double tpr[max_positives + 1];
double fpr[max_negatives + 1];

// 使用固定大小数组进行计算和操作

选择哪种方法取决于你的具体情况。如果不知道正例和负例的数量,则需要使用动态数组。如果事先知道最大数量,则可以使用固定大小数组。


原文地址: https://www.cveoy.top/t/topic/njEM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录