Inline vector operations in C

I use C to do some scientific calculations, and you need to navigate through many vectors.

I defined some basic Multiply and Add functions from the form

add(int size, double *out, double *x, double *y)

But for complex operations, code quickly becomes long and hard to read.

Is it possible to define built-in operators (V1 + V2)? Or any general recommendations that will facilitate the identification of the verification code for mathematical errors? Perhaps some #define shenanigans?

+3
source share
4 answers

At first I thought it was a C ++ question for some reason!

If you can use C ++, you can use an STL array (where size is a template parameter, not a stored value).

It might look something like this:

std::array<double, 7> a = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0};
std::array<double, 7> b = {0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0};
auto c = a + b;
auto d = a + b + c;

+. :

#include <array>
// ...
// (version 1) returns a new copy/temporary
template <class T, size_t size>
std::array<T, size> operator+(const std::array<T, size>& a, 
                              const std::array<T, size>& b)
{
    std::array<T, size> c;
    // add them however you want; simple version:
    for (size_t i = 0; i < size; ++i)
    {
        c[i] = a[i] + b[i];
    }
    return c;
}

// (version 2) no temporaries via rvalue ref/move semantic
template <class T, size_t size>
std::array<T, size>&& operator+(std::array<T, size>&& a, 
                                const std::array<T, size>& b)
{
    for (size_t i = 0; i < size; ++i)
    {
        a[i] += b[i];
    }
    return std::move(a);
}

:

auto c = a + b;       // invokes version 1
auto d = a + b + c;   // invokes version 1 for (b+c) 
                      // and then version 2 for a+(temp)

.

std:: array , , "" ( (ab) , typedefs ) .

+4

, Intel C. :

http://software.intel.com/sites/products/documentation/studio/composer/en-us/2011/compiler_c/optaps/common/optaps_par_cean_prog.htm

, :

int A[4] = { 1, 2, 3, 4 };
int B[4] = { 4, 3, 2, 1 };
int C[4];
C[:] = A[:] + B[:];

, , :

B[:] = cosf(C[:]);

, , , SSE/AVX.

+3

" " C. ++. ++ , . , :

  • , , . , , , ?

  • , , ( , ), "/" ( ) , :

    Filename f = Filename::MainFileSystem() / "folder1" / "folder2" / "file.txt";
    

    .

:

  • .

    result = vec1 + vec2 + vec3;
    

    , , , , , - , , .

  • You can perform some nifty tricks, such as smart pointers , that give you extra functionality without changing the original semantics of statements.

+2
source

Is it possible to define built-in operators (V1 + V2)?

No. But it is in C ++.

+1
source

All Articles