简体   繁体   中英

Calculate average of all data members in a vector of POD struct

I have a sensor that provides 3 different readings. I want to read the sensor X times and then get average of all readings:

#define NUM_DATA ((int)1000);

struct Data {
    int x;
    int y;
    int z;
}

Data getAverageData() {
    
    static std::vector<Data> vecData(NUM_DATA); // Vector for sensor data
    vecData.clear();
    
    for(int i = 0; i < NUM_DATA; i++) {
        int x = sensorGetX(); // from sensor
        int y = sensorGetY(); // from sensor
        int z = sensorGetZ(); // from sensor
        
        vecData[i] = {x, y, z};
    }
        
    // I am stuck here!!!
    Data average = std::accumulate(vecData.begin(), vecData.end(), 0.0,
                                     [&](int sum, Data d) {
            return sum + d.x;
        });    

    return average;
}

The Data struct is both used for keeping the data in the vector and also the average itself. I want to keep it this way. I know of course to do it the oldschool way but I want my code to look smart and I want to use latest facilities that c++11 or c++17 has to offer.

constexpr unsigned int num_data = 1000;

struct Data {
    int x;
    int y;
    int z;
}

Data getAverageData() {
    
    Data vecData_temp = {0, 0, 0};

    for(size_t i = 0; i < num_data; ++i) {
        vecData_temp.x += sensorGetX();
        vecData_temp.y += sensorGetY();
        vecData_temp.z += sensorGetZ();
    }

    vecData_temp.x /= num_data;
    vecData_temp.y /= num_data;
    vecData_temp.z /= num_data; 

    return vecData_temp;
}

I don't see a point creating a vector in this case. tried this light-weight code, only one local variable created.

Joonroo Taugh's answer is fine; but, if you wanted to use the latest c++17 features, I'd go about it like this, you almost had it correct anyway.

The only issue was you did not set up your collection correctly:

  • Use push_back instead of using the subscript operator;
  • Use reserve to allocate a block of data all at once, otherwise push_back will allocate when it runs out of capacity (it only allocates 1.5x more capacity every push_back that exceeds it);
  • Using clear is good to discard old data when using a static collection.

Note: I've added some helper operator overloads to make the average calculation look more math-y and easier to understand.

I would also consider passing in a vector reference to be filled or returning a local vector instance from the function as part of a std::pair<Data, std::vector<Data> so you can keep track of the last X values (which could be its own argument, up to you).

#include <numeric>
#include <vector>

//Default-construct members so they are not uninitialized.
struct Data {
    float x{};
    float y{};
    float z{};
}

Data operator/(const Data& lhs, float scalar) {
    return Data{lhs.x / scalar, lhs.y / scalar, lhs.z / scalar};
}

Data operator+(const Data& lhs, const Data& rhs) {
    return Data{x + rhs.x, y + rhs.y, z + rhs.z};
}

Data getAverageData() {
    constexpr std::size_t num_data{1000u}; //This could be an argument into the function...
    static std::vector<Data> vecData{};

    //Clear any data from the previous calculation.
    //Does not affect capacity.
    vecData.clear();
    vecData.reserve(num_data); //Reserve space all at once so push_back doesn't allocate.

    for(auto i = std::size_t{0u}; i < num_data; ++i) {
        vecData.emplace_back(sensorGetX(), sensorGetY(), sensorGetZ());
    }

    const auto average = std::accumulate(std::cbegin(vecData), std::cend(vecData), Data{},
    [&](Data sum, Data d) {
        return sum + (d / static_cast<float>(vecData.size()));
    });
    return average;
}

Following that if you don't want to use the result vector as a histogram, you can do exactly as Joonroo suggests and just use a temporary variable. Using operator overloads makes it much easier though:

#include <vector>

//Default-construct members so they are not uninitialized.
struct Data {
    float x{};
    float y{};
    float z{};
    Data& operator+=(const Data& rhs) {
        x += rhs.x;
        y += rhs.y;
        z += rhs.z;
        return *this;
    }
    Data& operator/=(float scalar) {
        x /= scalar;
        y /= scalar;
        z /= scalar;
        return *this;
    }
}

Data operator/(const Data& lhs, float scalar) {
    return Data{lhs.x / scalar, lhs.y / scalar, lhs.z / scalar};
}

Data operator+(const Data& lhs, const Data& rhs) {
    return Data{x + rhs.x, y + rhs.y, z + rhs.z};
}

Data getAverageData(std::size_t sensor_read_count = 1000) {
    Data average{};
    for(auto i = std::size_t{0u}; i < sensor_read_count; ++i) {
        average += Data{sensorGetX(),sensorGetY(),sensorGetZ()};
    }
    average /= static_cast<float>(sensor_read_count);
    return average;
}

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