在循环中创建实例并将它们保存到另一个向量中的最有效方法是什么

时间:2016-10-25 21:37:13

标签: c++ c++11

struct element {
    int start;
    int end;
};

我将课程声明如下

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++;
}   

这里我试图创建myClass的实例,如果两个连续路径之间的距离,我想让它们保持在同一个类中。我写了以下代码:

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++;
    }

虽然它运行没有错误,但不知何故它看起来效率不高。我试图使用指针,但它抛出异常。最有效的方法是什么?

2 个答案:

答案 0 :(得分:4)

您可以使用vector :: emplace方法构造一个对象,并将其一次性添加到容器中,从而避免复制。见emplace_back

答案 1 :(得分:2)

不确定(请注意确认),但在我看来,您的代码可以重写为

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()) || ( false == checkDistance(*i, *(i-1)) ) )
    {
        allObjects.emplace_back();
        k++;
    }

    allObjects.back().addElements(node);

    j++;
}