Search code examples
c++vectorstruct

c++ How to copy vector of struct into another vector of struct with kind of duplication


How to copy vector of struct into another vector of struct such as:

Let the first, and second vectors as:

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

where:

struct Linkedvalues{
    int indx;
    double Val;
};

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

in my program, I filled OriginalVector and i need to copy its values in NewVector with this duplication:

let OriginalVector has the following values:

{ (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 } 

I want to create NewVector as:

{ (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)

In order to do that, I did the following:

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

Solution

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

    That's the quick fix.

    There's no reason to create the new elements first, and then push them after.