In the code below, the Struct1 pointer in Struct2 should point consistently to a certain object of Struct1. Each of these structs is contained in a vector.
However, when I output the index variable of the Struct1 objects pointed to in the Struct2 objects, in some cases the wrong one is returned.
Why does a pointer to an object contained in a vector sometimes point to a different object in the vector?
struct Struct1
{
size_t index;
std::vector<size_t> data;
}
struct Struct2
{
Struct1 *s1;
}
class MyClass
{
std::vector<Struct1> s1s;
std::vector<Struct2> s2s;
size_t propIndex = 0;
void input(QByteArray &line)
{
if (line == "1") {
for (size_t i = s1s.size(); i <= propIndex; i++) {
s1s.push_back({ .index = i, .data= {} });
}
QByteArrayList list = getList();
for (auto id : list) s1s.at(propIndex).data.push_back(id.toULongLong());
}
else {
if (propIndex == s2s.size()) {
s2s.push_back({ .s1 = nullptr });
}
if (line == "2") {
size_t index = getIndex();
for (size_t i = s1s.size(); i <= index; i++) {
s1s.push_back({ .index = i, .data= {} });
}
s2s.at(propIndex).s1 = &s1s.at(index);
}
}
propIndex++;
}
QByteArrayList output()
{
QByteArrayList output;
for (auto s2 : s2s) {
output += QByteArray::number(s2.s1->index) + "\n";
}
return output;
}
}