在结构中使用 switch 引用结构中的数据C++

Referencing data in a struct using switch in C++

本文关键字:结构 数据 C++ 引用 switch      更新时间:2023-10-16

我的代码中有一个switch语句,可以在几种情况之间做出决定。 根据选择,我想加载一个特定的数据集,并将该数据集用于程序的其余部分。 其中一个挑战是我的结构中的数组将是任意长度的。 我试图避免的是针对每种情况多次重写我的主程序。 我的数据包含在我的 scenariodata.h 文件中,我的程序正在测试中.cpp。 现在它无法编译,但如果它按照我想要的方式工作,它应该在控制台中显示"10"。提前非常感谢。

测试.cpp

#include <iostream>
#include "scenarioData.h"
int main(){
int choice = 1;
//initialize a blank struct with generic name 'sd'
sd_fmt sd;
switch((int) choice){
//Make a decision of which data set to use
case 1:
std::cout << "Using data1n";
sd = data1;
break;
case 2:
std::cout << "Using data2n";
sd = data2;
break;
}
//From here on do all my work with general variable name 'sd'
std::cout << sd.speed[1];  //Should show 10 in the console
return 0;
}

场景数据.h

struct sd_fmt {
double *speed;
};
struct sd_fmt {
double speed[4] = {1,10,100,1000};
} data1;
struct sd_fmt{
double speed[5] = {2,200,2000, 20,20000};
} data2;

我已经将片段更新为更现代的C++风格。

结构定义与结构实例的声明混淆。不是创建包含指针的结构,而是使用 std::vector。 应尽可能避免使用指针。

该矢量具有多种优点,包括大小可变。 向量的初始化也很简单。 如果向量具有已知大小,则 at(( 成员可用于访问特定元素。

switch 语句复制了不理想的向量。 如果向量非常大,那么使用对向量的引用会更有效。对于这个小例子,这不是问题。

#include <vector>
#include <iostream>
using sd_fmt = std::vector<double>;
sd_fmt data1 = {1,10,100,1000};
sd_fmt data2 = {2,200,2000, 20,20000};
int main(){
int choice = 1;
//initialize a blank struct with generic name 'sd'
sd_fmt sd;
switch((int) choice){
//Make a decision of which data set to use
case 1:
std::cout << "Using data1n";
sd = data1;
break;
case 2:
std::cout << "Using data2n";
sd = data2;
break;
}
//From here on do all my work with general variable name 'sd'
std::cout << sd.at(1);  //Should show 10 in the console
return 0;
}