在结构中使用 switch 引用结构中的数据C++
Referencing data in a struct using switch in C++
我的代码中有一个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;
}
相关文章:
- 如何在C++中序列化结构数据
- 正在转换结构数据的字节序
- C++ - 使用结构数据类型将单词中的单个小写字符更改为大写,反之亦然
- 在结构数据类型中更改每个字符的 ASCII 值
- C++ - 检查结构数据类型中的单词是否为回文
- 如何将结构数据成员传递到函数中
- 在std::线程中使用已分配的结构数据
- 将结构数据存储在循环缓冲区中
- 通过指针算法访问结构数据成员
- 将结构数据类型传递给 C++ 中的命名管道
- CLI/C# 将 std::vector<> 结构数据传递给 C#
- 使用来自 C 的内存地址的 Julia 读取/写入结构数据
- CPP 在读取结构数据时无限循环错误?
- 为什么C++编译器不优化对结构数据成员的读取和写入,而不是不同的局部变量?
- 使用Hazelcast替换共享内存结构数据
- 带有结构数据的 Gmock
- 结构数据D = {0}和结构数据D = {}之间是否存在任何区别
- 有没有办法将数组行为作为静态结构数据成员?
- 使用函数操作结构数据类型的值
- 有关结构数据'getting'的性能