'How to access a specific point in the file?

I have a file with points (x, y, z). How do I access a certain point from the file?

example file:

2 1 6
1 3 7
3 5 4

I want to refer to the points from the file in this way:

arr[0].x = 2;
arr[0].y = 1;
arr[0].z = 6;
arr[1].x = 1;
arr[1].y = 3;
arr[1].z = 7;
arr[2].x = 3;
arr[2].y = 5;
arr[2].z = 4;

code:

int main() {
    vector<Point> point;
    Point tmp;
    int n = 3;
    Point arr[n];

    ifstream in;
    in.open("E:\\Points.txt");

    if (!in.is_open())
        cout << "Cannot open the file \n";
    else{
        while (in >> tmp.x >> tmp.y >> tmp.z){
            point.push_back(tmp);

            geometricMedian(arr, n);
        }
        in.close();
        return 0;
    }
}
c++


Solution 1:[1]

I'd learn about overloading stream operators and then how to use the istream iterators.

struct Points
{
    int x;
    int y;
    int z;
    friend std::istream& operator>>(std::istream& is, Points& p)
    {
        return is >> p.x >> p.y >> p.z; //TODO error handling
    }
};

That construct allows to read the data from the stream into the structure, thus enabling the following operation:

std::vector<Points> v{std::istream_iterator<Points>{sin}, std::istream_iterator<Points>{}};

Under the hood, it just iterates over the data in the stream and pushes new data to the vector.

In the end, one can refer to the point in vector using vector's indexing operator+point's field name.

Unrelated side note: Per analogiam, similar thing can be achieved for output:

    friend std::ostream& operator<<(std::ostream& os, const Points& p)
    {
        return os << ' ' <<  p.x << ' ' <<  p.y << ' ' << p.z;
    }

effectively enabling constructs like this: std::cout << v[0] << '\n';

Live demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alagner