C++: Sorting array of struct containing StaticString<> member
Hello everybody,
I'm facing a strange issue after moving from array of uint8 to StaticString<>.
- I had a C++ program using array of uint8 for sharing strings between C++ and IEC61131 program.
- Those "strings" were members of a struct.
- I used an array of those structs.
- I used std::sort() to order the structs by a numerical member.
Example:
// struct definition struct udtItem { uint8 name[8] = { 0 }; int32 value = 0; }; // array declaration udtItem Items[300];
/* ... code that fills the members of the structs member .name could be empty ... */ // sorting code std::sort(std::begin(Items), std::begin(Items) + 300, [](const udtItem &a, const udtItem &b) { return a.value < b.value; });
Everything worked correctly.
Then, I decided to move from array of uint8 to StaticString<>.
// struct definition struct udtItem { StaticString<8> name = ""; //uint8 name[8] = { 0 }; int32 index = 0; };
Using std::sort() this time creates a bad error:
All the StaticStrings that were empty before the sorting are filled with random values (it seems that are filled with the content of the same member from other structs of the array)
Is this an expected behavior?
Thanks,
Marcello
This discussion has been closed.
Comments
Hello,
please try to store the data into vector, do you have the same result (see attached project)?
I assume this behavior can be caused by sort algorithm.
Result:
BR Eduard
Hello Eduard,
I tried but the result is the same.
I found a not-so-elegant workaround for now (filling empty strings with known characters before sorting and clearing later).
I'll update this discussion if I'll find a better solution.
Thanks,
Marcello