0

I'm trying to incorporate the STL std::valarray into my program. I want to be able to change parts of my program from something like this

for (unsigned int d = 0; d < DIM; ++d) {
    position[d] += dt*(velocity[d] + a*force_new[d]);
    force_old[d] = force_new[d];
}

to this

    position += dt*(velocity + a*force_new);
    force_old = force_new;

and

for (const auto& particle: particles) {
    for (unsigned int d = 0; d < DIM; ++d) {
        std::cout << particle.position[d] << " ";
    }
    std::cout << std::endl;
}

to something like

for (const auto& particle: particles) {
    for(const auto& item: particle.position) std::cout << item << " ";
    std::cout << std::endl;
}

Currently, the data structure I use looks like follow:

struct Particle{
    std::array<double, DIM> position; 
    std::array<double, DIM> velocity;
    std::array<double, DIM> force_new;
    std::array<double, DIM> force_old;
    void update_position();
};

I changed this part of my code to

struct Particle{           
    std::array<std::valarray<double>, DIM> position; 
    std::array<std::valarray<double>, DIM> velocity;
    std::array<std::valarray<double>, DIM> force_new;
    std::array<std::valarray<double>, DIM> force_old;
    void update_position();
};

However, I my code does not compile if I change my code as shown above. The compiler throws errors like

nbody.cpp: In member function ‘void Particle::update_position(double)’:
nbody.cpp:83:33: error: no match for ‘operator*’ (operand types are
‘const double’ and ‘std::array<std::valarray<double>, 2>’)
position += dt*(velocity + a*force_new);

and

    nbody.cpp: In member function ‘void Nbody::print_data() const’:
    nbody.cpp:45:60: error: no match for ‘operator<<’ (operand types are
    ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const
    std::valarray<double>’) for(const auto& item: particle.position)
std::cout << item << " ";
Gilfoyle
  • 3,282
  • 3
  • 47
  • 83

0 Answers0