mardi 25 octobre 2016

What is the most efficient way to create instances in loop and save them into another vector

struct element {
    int start;
    int end;
};

I declared class as below

class myClass {
public:
    myClass();
    void addElements(element);
    virtual ~myClass();
private:
    int elementCount = 0;
    std::vector<element> includedElems;
};

void motionSet::addVectors(motionVector mv) 
{
    /*A function for adding motion vectors for specific object*/
    includedVectors.push_back(mv);
    vectorCount++;
}   

Here I am trying to create instances of myClass and if the distance between two consecutive paths, I want to keep them in same class. I wrote the following code:

std::vector<myClass> allObjects;
element path;
auto j=series2.begin();
for(auto i = series1.begin(); i < series1.end() ;++i)
{
    path.start = *i;
    path.end = *j;
    if(i!= series1.begin())
    {
        if(checkDistance(*i,*(i-1)))
        {
            //Here I want to add elements to already created instance of myClass, but does not want to resize allObjects. --> PROBLEMATIC PART
            myClass sameObject = *(allObjects.end()-1);
            sameObject.addElements(node);
            allObjects.erase(allObjects.end()-1);
            allObjects.push_back(sameObject);
        }
        else
        {//Here I want to create a new instance of myClass and want to add it to allObjects
            myClass anotherObject;
            anotherObject.addElements(node);
            allObjects.push_back(anotherObject);
            k++;
        }
    }
    else
//Want to create an instance in the first iteration
        {
            myClass firstObject;
            firstObject.addElements(node);
            allObjects.push_back(firstObject);
            k++;
        }
        j++;
    }

Although it runs without errors, somehow it does not seem efficient. I tried to use pointer, but it throws exceptions. What is the most efficient way to do this?

Aucun commentaire:

Enregistrer un commentaire