[英]How would I create a structure that allows me to define multiple objects with multiple values?
I need to create a structure that allows me to define an x number of points (the number of points changes at run time) in a 3-D coordinate system. 我需要创建一个结构,该结构允许我在3-D坐标系中定义x个点(运行时点数变化)。 Each point has an x, y, and z value.
每个点都有一个x,y和z值。 So far I have a basic structure like this, but I need it to be able to have multiple points, each with their own values.
到目前为止,我具有这样的基本结构,但我需要它能够具有多个点,每个点都有自己的值。
struct point {
int point_num;
double x;
double y;
double z;
};
Thanks! 谢谢!
If point_num
is a non-contiguous but unique identifier you could use std::map<int, point>
and remove the identifier from the struct. 如果
point_num
是不连续但唯一的标识符,则可以使用std::map<int, point>
并从结构中删除该标识符。 That way you get O(log(N)) lookup using the index. 这样,您就可以使用索引进行O(log(N))查找。
If point_num
values are unique and contiguous, use std::vector<point>
- again the id field is superfluous, as the location in the vector provides an indexing value for you. 如果
point_num
值是唯一且连续的,请使用std::vector<point>
-同样,id字段也是多余的,因为向量中的位置为您提供了索引值。
Read up a bit on STL, especially containers , before you go much further. 在继续之前,请先阅读一下STL,尤其是容器 。
Use a container. 使用容器。
std::vector<point>
would be the simplest. std::vector<point>
将是最简单的。 If there are no duplicate points, use std::set<point>
. 如果没有重复的点,请使用
std::set<point>
。
You could use vector
, the standard C++ container: 您可以使用
vector
,这是标准的C ++容器:
#include <vector>
using namespace std;
int main() {
vector<point> points;
for (int i = 0; i < numberOfPoints; ++i) {
point p = {i, ..., ..., ...}; // Obtain coordinates somehow (with stdin, rand(), or whatever you want)
points.push_back(p);
}
return 0;
}
If you need to, you can wrap a vector
in a struct or a class. 如果需要,可以将
vector
包装在结构或类中。
You should probably create a struct that represents one point, and have an array or vector of points. 您可能应该创建一个代表一个点的结构,并具有点的数组或向量。
But, if from some reason it has to be one struct, you can do: 但是,如果由于某种原因它必须是一个结构,则可以执行以下操作:
#include <vector>
struct point {
double x;
double y;
double z;
};
struct x_points {
vector<point> v;
};
Or you can define point
inside x_points
: 或者,您可以在
x_points
内定义point
:
#include <vector>
struct x_points {
struct point {
double x;
double y;
double z;
};
vector<point> v;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.