I am rather inexperienced at C/C++ so hopefully my question will be easy to answer.

I have created a struct which contains vectors. I read in data from a file into the various vectors in each struct do a bit of maths, write the results to another file, clear the vectors and repeat.

Is there a way I can clear all the vectors in a struct at a time? I am finding as I add new vectors to the struct I have to continue to add in more and more lines to clear the vectors. If I was to forget to clear a vector I wouldn't get an error message and it would ruin the aim of the program.

I'll include some of my code although it is rather long ugly mess :-|

struct data {
  vector< float > px;
  vector< float > py;
  vector< float > pz;
  vector< float > energy;
  vector< float > transmom;
  vector< float > ip;
  vector< float > ipsig;
  vector< float > confidence;
};
data piplus;
data kminus;
data piminus;
data kplus;

// a loop containing lots of boring formula

    piplus.px.clear();
    piplus.py.clear();
    piplus.pz.clear();
    piplus.energy.clear();
    piplus.transmom.clear();
    piplus.ip.clear();
    piplus.ipsig.clear();
    piplus.confidence();
    kminus.px.clear();
    kminus.py.clear();
    kminus.pz.clear();
    kminus.energy.clear();
    kminus.transmom.clear();
    kminus.ip.clear();
    kminus.ipsig.clear();
    kminus.confidence();
    piminus.px.clear();
    piminus.py.clear();
    piminus.pz.clear();
    piminus.energy.clear();
    piminus.transmom.clear();
    piminus.ip.clear();
    piminus.ipsig.clear();
    piminus.confidence.clear();
    kplus.px.clear();
    kplus.py.clear();
    kplus.pz.clear();
    kplus.energy.clear();
    kplus.transmom.clear();
    kplus.ip.clear();
    kplus.ipsig.clear();
    kplus.confidence.clear();

// more boring formula before end of loop

// surely there is a more efficient way than doing this?

Is there a way I can clear all the vectors in a struct at a time?

No, not really. But you can minimize the redundant code by putting all of this in a function:

void clear_data(data obj)
{
    piplus.px.clear();
    piplus.py.clear();
    piplus.pz.clear();
    piplus.energy.clear();
    piplus.transmom.clear();
    piplus.ip.clear();
    piplus.ipsig.clear();
    piplus.confidence();
}

Then the long string of clears turns into:

clear_data(piplus);
clear_data(kminus);
clear_data(piminus);
clear_data(kplus);

If you have a *plus and *minus object for every prefix then you can add another wrapper:

clear_data(data o1, data o2)
{
  clear_data(o1);
  clear_data(o2);
}

And your code is minimized to:

clear_data(piplus, piminus);
clear_data(kplus, kminus);
This article has been dead for over six months. Start a new discussion instead.