c++如何从硬编码结构中获取数据

c++ how to get data out of a hardcoded struct?

本文关键字:结构 获取 数据 编码 c++      更新时间:2023-10-16

我有一个结构,其中有硬编码的数据,但我不知道如何使用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 }
}};

查看实时演示