C ++ for several data types (vector RPN calculator)

I developed a fast and basic vector arithmetic library in C ++. I call the program from the command line when I need a quick cross-product or the angle between vectors. I do not use Matlab or Octave or related, because the startup time is longer than the calculation time. Again, this is for very simple operations.

I am expanding this program and I will make it work as an RPN calculator for operations like:

1 2 3
4 5 6
x
out: -3 6 -3

(give one vector, another vector and a "cross" operator, spit out the transverse product)

The stack must accept 3d vectors or scalars for operations such as:

1 2 3
2
*
out: 2 4 6

- , . ( - , , ).

, Vector double?

.

+3
3

Operand, double Vector :

struct Operand
{
    double scalar_;
    Vector vector_;
    bool isVector_;
};

( isVector_ true, , false, )

std::stack<Operand>.

( , ) - boost::variant, - , Operand, , , .

+1
+3

. . , . , . , , .

Unions are a bit hacky because they make using objects more complicated. The compiler does not know how to create, destroy, or copy them, because many objects can use the same memory. Here is a small example of how I would do this if I would like to save memory (normal, an enumeration takes four bytes and is therefore inefficient for memory, but don't forget that;)

#include <cstdlib>
#include <iostream>

struct Vector
{
    double x, y, z;
};

struct Element
{
    enum Type { SCALAR, VECTOR };
    Type type;
    union {
        double scalar;
        Vector v;
    } data;
};

int main(void)
{
    Element vector_element;
    vector_element.type = Element::VECTOR;
    vector_element.data.v.x = 1;
    vector_element.data.v.y = 2;
    vector_element.data.v.z = 3;

    Element scalar_element;
    scalar_element.type = Element::SCALAR;
    scalar_element.data.scalar = 3.142;

    std::cout << "The size of type Element without enum would be: " << (sizeof(Element) - sizeof(Element::Type)) << " bytes." << std::endl;

    return EXIT_SUCCESS;
}

By the way, for some strange reason, this results in 28 bytes. I expected 3 * 8 = 24 bytes.

+3
source

Source: https://habr.com/ru/post/1745479/


All Articles