mardi 30 août 2022

C++: Access to element modifies object state

I have the case where i would like to be able to work on cartesian points (assumme 2d, double), with possibility of translation cartesian coordinates to polar coordinates.

I would also like to be able to override one-type point with other-type point, safely, and not to worry wheter it was performed or not. I was thinking of separate object storing two coresponding vectors, guarding access.

struct CartesianPoint
{
    double x, y;
};

struct PolarPoint
{
    double r, phi;
};

class Polar2Cartesian
{
public:
    Polar2Cartesian(const std::vector<CartesianPoint>&);
    void GetPolar(std::vector<PolarPoint>&) const;
// accessing vector of points in selected coordinates system, after modifications
    void GetCartesian(std::vector<CartesianPoint>&) const;
private:
    std::vector<CartesianPoint> cartesianPoints; // gets initialized in constructor by copying
    std::vector<PolarPoint> polarPoints; // gets initialized in constructor by recalculation
}

I wish i could perform operation of overriding points in both formats by changing one only. Here is example.

int main()
{
    std::vector<CartesianPoint> cp;

    // fill in vector
    ...
    ...

    Polar2Cartesian p2s{cp};
    
    int i; // just index
    i = ... //setting value (assume is in valid range do reverence elements of cp)

    p2c[i] = PolarPoint{1.0, 2.0}; // updates i-th point in both Polar and Cartesian coordinates
    // or
    p2c[i] = CartesianPoint{3.0, 4.0}; // updates i-th point in both Polar and Cartesian coordinates
    ...
    // some other work
    ...
    
    std::vector<PolarPoint> pp_after{};
    std::vector<CartesianPoint> cp_after{};

    p2c.GetPolar(pp_after);
    p2c.GetCartesian(cp_after);

    // have to vectors of SAME points in different coordinate systems
}

I am having hard time searching for simple solution of this problem. I will be happy to hear any sugesstion.

Aucun commentaire:

Enregistrer un commentaire