我需要创建一个结构,允许我在三维坐标系中定义x个点(运行时点的数量变化)。每个点都有x,y和z值。到目前为止,我有一个这样的基本结构,但我需要它能够有多个点,每个点都有自己的值。
struct point {
int point_num;
double x;
double y;
double z;
};
谢谢!
答案 0 :(得分:4)
如果point_num
是非连续但唯一的标识符,则可以使用std::map<int, point>
并从结构中删除标识符。这样你就可以使用索引获得O(log(N))查找。
如果point_num
值是唯一且连续的,请使用std::vector<point>
- id字段也是多余的,因为向量中的位置为您提供了索引值。
在你走得更远之前,先阅读一下STL,特别是containers。
答案 1 :(得分:2)
使用容器。 std::vector<point>
将是最简单的。如果没有重复点,请使用std::set<point>
。
答案 2 :(得分:1)
您可以使用标准C ++容器vector
:
#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;
}
如果需要,可以将vector
包装在结构或类中。
答案 3 :(得分:1)
你应该创建一个代表一个点的结构,并且有一个数组或点向量。
但是,如果由于某种原因它必须是一个结构,你可以这样做:
#include <vector>
struct point {
double x;
double y;
double z;
};
struct x_points {
vector<point> v;
};
或者您可以在point
内定义x_points
:
#include <vector>
struct x_points {
struct point {
double x;
double y;
double z;
};
vector<point> v;
};