简体   繁体   中英

C++ data type best suited for physics vectors like velocity

Beginner programmer here. I want to find the best data structure in C++ to deal with physics vectors such as position, velocity, etc.

Currently I'm using std::array<double,dimension> , where the dimension is fixed throughout the program, but it's not terribly convenient since there is no built-in arithmetic operations. I read about std::valarray but a lot of references discourage using it, and something like std::vector is not optimal since the dimension is fixed.

Is there such a type or should I stop being lazy and overload the std::array operators?

There are vector math libraries you can get, and some of them are free for academic use.

To roll your own isn't difficult, but what you should do is create your own class that contains the std::array or std::vector, provide forwarding methods that you might need (like array index), and math overloads as you need them. Ideally it should be a template class, like std::array is, so you can specify the dimension at compile time as you currently do.

It is not a good idea to add operator overloads to the standard containers for integral types, as you never know what other code you might compile that happens to contain the same container, and would clash.

If you are using GCC you can use GCC's SIMD extensions .

Example - LIVE :

#include <iostream>
#include <x86intrin.h>

typedef double v4d __attribute__ ((__vector_size__ (sizeof(double)*4)));

int main(){
    v4d x{1,2,12};
    v4d y{3,4,2};
    auto z = 1.5+x*y;
    for(size_t i = 0; i < 3; ++i)
        std::cout << z[i] << std::endl;
    return 0;
}

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