c ++如何将struct的向量复制到另一个带有重复类型的struct向量中

时间:2014-09-29 21:02:19

标签: c++ vector struct

如何将struct的vector复制到另一个struct的向量中,如:

让第一个和第二个向量为:

std::vector <myStruct> OriginalVector 
std::vector <myStruct> NewVector  

其中:

struct Linkedvalues{
    int indx;
    double Val;
};

struct myStruct{
    std::vector<int> Id;
    double avg;
    std::vector<Linkedvalues> lValues;
    double sum= 0.0;
};

在我的计划中,我填写了OriginalVector,我需要在NewVector中复制其值并重复:

OriginalVector具有以下值:

{ (1, 2), 0.6, {(1, 0.5), (3,0.1), (5,0.7)}, 1.5 } 
{ (1, 3), 0.5, {(1, 0.2), (4,0.9), (5,0.7)}, 3.1 } 
{ (2, 3), 0.1, {(3, 0.4), (2,0.2), (5,0.7)}, 4.2 } 
{ (3, 5), 0.3, {(2, 0.1), (3,0.6), (5,0.7)}, 7.5 } 

我想将NewVector创建为:

{ (1, 2), 0.6, {(1, 0.5), (3,0.1), (5,0.7)}, 1.5 } 
{ (2, 1), 0.6, {(1, 0.5), (3,0.1), (5,0.7)}, 1.5 } // also add the same previous 
                                                   //vector but swap (1,2) to (2,1)  

{ (1, 3), 0.5, {(1, 0.2), (4,0.9), (5,0.7)}, 3.1 } 
{ (3, 1), 0.5, {(1, 0.2), (4,0.9), (5,0.7)}, 3.1 }  // also add the same previous 
                                                   //vector but swap (1,3) to (3,1)

{ (2, 3), 0.1, {(3, 0.4), (2,0.2), (5,0.7)}, 4.2 } 
{ (3, 2), 0.1, {(3, 0.4), (2,0.2), (5,0.7)}, 4.2 } //also add the same previous 
                                                   //vector but swap (2,3) to (3,2)

{ (3, 5), 0.3, {(2, 0.1), (3,0.6), (5,0.7)}, 7.5 } 
{ (5, 3), 0.3, {(2, 0.1), (3,0.6), (5,0.7)}, 7.5 }  //also add the same previous 
                                                   //vector but swap (3,5) to (5,3)

为了做到这一点,我做了以下事情:

int i=0;
while (i < OriginalVector.size())
{
 auto it = (std::make_pair(OriginalVector[i].id.front(), OriginalVector[i].id.back()));
 auto itt = (std::make_pair(OriginalVector[i].id.back(), OriginalVector[i].id.front()));

// Here I fail to insert it and itt with the rest of OriginalVector[i] members into NewVector 
++i;
}

1 个答案:

答案 0 :(得分:3)

std::vector <myStruct> NewVector;
NewVector.reserve(OriginalVector.size()*2);
for(auto&& v : OriginalVector) {
    NewVector.push_back(v);
    NewVector.push_back(v);
    auto& x = NewVector[NewVector.size()-1].Id;
    std::swap(x[0], x[1]);
}

这是快速修复。

没有理由先创建新元素,然后再推送它们。