Construct Sensor Packet Placement

#include <iostream>
#include <cstdint>
#include <new>
#include <type_traits>
using namespace std;

struct SensorPacket{
    int id; int value;
};

int main() {
    int index, id, value;
    cin >> index >> id >> value;

    //creating raw sized + aligned memory

    using storage = std::aligned_storage_t<sizeof(SensorPacket), alignof(SensorPacket)>;

    //creating buffer at the initialised raw storage to hold 3 structs as elements

    storage sensor_memory[3];

    //placing the struct with user values at the indexed buffer position

    SensorPacket *ptr = new (&sensor_memory[index]) SensorPacket{id, value};

    cout << ptr->id << " "<< ptr->value;

    ptr->~SensorPacket();

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

1 50 900

Expected Output

50 900