c++如何从硬编码结构中获取数据
c++ how to get data out of a hardcoded struct?
我有一个结构,其中有硬编码的数据,但我不知道如何使用c++来显示数据。我正在尝试的是:
#include <iostream>
using namespace std;
const int MAX = 8;
struct test {
int x[MAX] = { 16, 21, 308, 45, 51, 63, 17, 38 };
float y[MAX] = { 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5 };
int z[MAX] = { 8, 7, 6, 5, 4, 3, 2, 1 };
} id[MAX] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int main() {
for (int counter = 0; counter < MAX; counter++) {
cout << id[counter].x << ", " << id[counter].y << ", "<< id[counter].z << endl;
}
}
我建议您更改数据布局:
struct Triplet
{
int x;
float y;
int z;
};
接下来,制作一个值的容器:
std::vector<Triplet> test;
或
Triple test[MAXIMUM_CAPACITY];
这将使您的初始化更容易
它还可以通过使数据缓存中的相关数据更紧密地放在一起来加快程序的速度。
我不知道如何使用c++来显示数据。
您一直在讨论硬编码阵列的使用
您不需要将struct
的尺寸加倍。任何struct
初始化都将为其成员保留必要的内存。
你可能想写一些类似的东西
#include <iostream>
using namespace std;
const int MAX = 8;
struct test
{
int x; // A simple int
float y; // A simple float
int z; // A simple int
} const id[MAX] = // Preserve the dimension. Note the const, to prevent changing the
// hardcoded values.
// Initialize the triples as needed
{ { 16, 1.5, 8 } ,
{ 308, 2.5, 7 } ,
// Place more triples here ...
{ 38, 8.5, 1 }
};
int main()
{
for (int counter = 0; counter < MAX; counter++)
{
cout << id[counter].x << ", " << id[counter].y << ", "<< id[counter].z << endl;
}
return 0;
}
查看实时演示
编写这篇文章的惯用c++方法是
struct test {
int x; // A simple int
float y; // A simple float
int z; // A simple int
};
std::array<test,MAX> id {{
{ 16, 1.5, 8 } ,
{ 308, 2.5, 7 } ,
// Place more triples here ...
{ 38, 8.5, 1 }
}};
查看实时演示
相关文章:
- 从字符串中获取结构的大小
- 如何在结构初始化中获取成员C++
- 从 cin 获取 c++ 中结构中多个枚举的输入
- 如何通过向量中的结构 id 获取索引号
- 获取结构 c++ 中元素的索引
- 如何获取结构C++的输入
- 使用加速融合获取结构名称
- 如何使用值获取结构的索引
- 如何获取结构体成员的地址
- 结构化绑定,无需复制即可获取子向量的连续元素
- 在通过 P/Invoke 获取的 C++ 结构上设置 C# 回调
- 获取指向映射内结构的指针
- 从行分析中获取结构
- 在模板实例化期间获取原始结构/类名C++
- 如何从 GIFLIB 保存图像结构中获取 RGB 颜色数据
- 获取结构的 UUID
- 如何直接从 FILETIME 结构获取/设置和获取秒数
- 从知道其结构类型的实例中获取值
- 如何使用结构C++获取从函数中生成的最大值
- 从接口层次结构获取接口