简体   繁体   中英

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. Each point has an x, y, and z value. 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. That way you get O(log(N)) lookup using the index.

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.

Read up a bit on STL, especially containers , before you go much further.

Use a container. std::vector<point> would be the simplest. If there are no duplicate points, use std::set<point> .

You could use vector , the standard C++ container:

#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.

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 :

#include <vector>
struct x_points {
        struct point {
            double x;
            double y;
            double z;
        };

        vector<point> v;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM