Home > Enterprise >  C Qt : push_back doesn't work correctly
C Qt : push_back doesn't work correctly

Time:10-02

I'm trying to write a code which reads .stl files, and gathers the informations in an std::vector<Triangle*>triangles. When I'm using push_back, it erases all the previous values in triangles and replaces all of them by the last value I'm trying to push_back.

Here is my code :

Mesh.h: struct Triangle {
    Node* nodes[3];
    double normal[3]; };

struct Node {
    double coo[3]; };

public:
    std::vector<Triangle*> triangles;

Mesh.cpp void dm::Mesh::loadSTL(const QString p_file) //----------------------------------------------------------------------------- {
    //Open the STL file
     QFile file(p_file);

    //READ FILE

    file.open(QIODevice::ReadOnly | QIODevice::Text);

    Node *vn = new Node;
    Node *vertex1 = new Node;
    Node *vertex2 = new Node;
    Node *vertex3 = new Node;
    Triangle *triangle = new Triangle;
    *triangle->nodes = new Node;
    QString line;
    QTextStream in(&file);
    line = in.readLine();                   // solid

    while(true)
    {
        line = in.readLine().trimmed();     //facet or endsolid
        if(line.trimmed().startsWith("endsolid"))
        {
            break;
        }
        *vn = getCoordinateFromString(line);

        line = in.readLine();               //outer loop
        line = in.readLine().trimmed();     //vertex 1
        *vertex1 = getCoordinateFromString(line);
        line = in.readLine().trimmed();     //vertex 2
        *vertex2 = getCoordinateFromString(line);
        line = in.readLine().trimmed();     //vertex 3
        *vertex3 = getCoordinateFromString(line);
        line = in.readLine();               //endloop
        line = in.readLine();               //endfacet

        triangle->nodes[0] = vertex1;
        triangle->nodes[1] = vertex2;
        triangle->nodes[2] = vertex3;

        for(int i = 0; i<3 ; i  ){
            triangle->normal[i] = vn->coo[i];
        }

        triangles.push_back(triangle);
    }
    file.close();

}

CodePudding user response:

The problem is that you create the triangle once and keep pushing the pointer to that triangle into the vector. Meaning any change to the pointer will affect all items in the vector (because they all point to the same instance).

You should move the construction of the triangle in the while loop (Triangle *triangle = new Triangle;) This makes sure you create a new pointer every time.

  •  Tags:  
  • c qt
  • Related