I have an array that looks like this (the real one is much longer, with around 150 elements):
static const MyConfig m_Original[] =
{
{0x01, 0x04, 0},
{0x02, 0x0A, 0},
{0x03, 0x54, 0},
{0x01, 0x05, 0},
{0xA1, 0xE5, 0},
{0xA2, 0x6B, 0},
{0xA3, 0x2B, 0},
{0xA1, 0xE3, 0},
};
In certain cases I would like to use almost the same array, but with a couple changes.
So I did a "patch" array:
static const MyConfig m_Patch[] =
{
{0x01, 0x0F, 0},
{0x02, 0x0F, 0},
{0xA1, 0xFF, 0},
};
Note that the it is the only second value of each element (the value) the one that changes.
So, I would like to replace those 3 (maybe more in real life) values from the original array. And! as you see, some value are repeated, all repetitions should be replaced.
The two immediate solutions are:
Just create a new array with the needed values (but then I'm allocating a big array that I will never use.
Write a
forloop comparing each element of each array and replacing if exists, which doesn't seem elegant (maybe I'm wrong (?))
The question: is there an optimal way of achieving this?
So at the end I would like m_Original to look like:
{0x01, 0x0F, 0}, => Replaced
{0x02, 0x0F, 0}, => Replaced
{0x03, 0x54, 0},
{0x01, 0x0F, 0}, => Replaced
{0xA1, 0xFF, 0}, => Replaced
{0xA2, 0x6B, 0},
{0xA3, 0x2B, 0},
{0xA1, 0xFF, 0}, => Replaced
FYI:
typedef struct
{
uint16_t Addr;
uint16_t Value;
uint32_t time;
} MyConfig ;
EDIT: m_Original should not be sorted, its order is important
Addrwhen matching. Is that the case? A simple solution would be to index your "patch" array with something likestd::unordered_map<uint16_t, const MyConfig*>and then use that in a loop. This avoids needing to loop over every patch element for every candidate.std::lower_boundfor example) without needing to construct any index at runtime.std::unordered_map<uint16_t , MyConfig>?