[ROOT] Q: Write/Read a ROOT file with STL vector?

From: Junichi.Tanaka@cern.ch
Date: Sat Jul 19 2003 - 06:50:51 MEST


Hello,

I'd like to write and read the ROOT file,
which is created by the following codes:
MyC.h, MyC.cxx, MyCLinkDef.h, simple-write.C, simple-read.C.
(I use ROOT of v3.05.05 at RH7.3 PC.)

First I made a shared library "libMyC.so" by my Makefile:
-----
g++ -O -Wall -fPIC -D_REENTRANT -I/usr/local/root/v3.05.05/include -c MyC.cxx
rootcint -f MyCDict.cxx -c MyC.h MyCLinkDef.h
g++ -O -Wall -fPIC -D_REENTRANT -I/usr/local/root/v3.05.05/include -c MyCDict.cxx
g++ -shared -O MyC.o MyCDict.o -o  libMyC.so 
-----
Then I could run ".x simple-write.C" with no error.
I could run ".x simple-read.C" with no error
but the size of vector is always 0.
How do I modify my codes to get the correct size of vector
and to access the data stored at the ROOT files?

//
// MyC.h
//
#include "TObject.h"
#include <vector>
#include "TLorentzVector.h"

class MyClass : public TObject
{
private:
  Int_t m_id;
  std::vector<double> List;
  std::vector<TLorentzVector> Vect;

public:
  MyClass() {};
  virtual ~MyClass() {};
  Int_t GetID() { return m_id; }
  void SetID(Int_t x) { m_id = x; }

  void SetList(double x) { List.push_back(x); }
  std::vector<double> * GetList() { return &List; }
  void View() { cout << List.size() << endl; }

  void SetP(TLorentzVector &v) { Vect.push_back(TLorentzVector(v)); }
  std::vector<TLorentzVector> * GetPList() { return &Vect; }
  void PView() { cout << Vect.size() << endl; }

  ClassDef(MyClass,1)
};

//
// MyC.cxx
//
#include "MyC.h"

ClassImp(MyClass);

//
// MyCLinkDef.h
//
#ifdef __CINT__
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
#pragma link C++ class MyClass;
#pragma link C++ class std::vector<double>;
#pragma link C++ class std::vector<TLorentzVector>;
#endif

//
// simple-write.C
//
{
  gSystem.Load("libPhysics.so");
  gSystem.Load("libMyC.so");
  TFile *f = new TFile("simple-class.root","RECREATE");
  TTree *t = new TTree("t","Simple Class");
  MyClass *m = new MyClass();
  // t->Branch("my","MyClass",&m,16000,0);
  t->Branch("my","MyClass",&m);
  
  for (Int_t i=0;i<5;++i) {
    m->SetID(i*2);
    int n = 0;
    for (Int_t j=0;j<i+1;++j) {
      ++n;
      m->SetList(double(i+j)*1.5);
      m->SetP(TLorentzVector(1,2,i,j));
    }
    cout << n << endl;
    t->Fill();
  }

  f->Write();
}

//
// simple-read.C
//
{
  gSystem.Load("libPhysics.so");
  gSystem.Load("libMyC.so");
  TFile *f = new TFile("simple-class.root");
  TTree *t = (TTree*)f->Get("t");
  MyClass *m = new MyClass();
  TBranch *b = t->GetBranch("my");
  b->SetAddress(&m);

  Int_t nEnt = t->GetEntries();
  for (Int_t i=0;i<nEnt;++i) {
    b->GetEntry(i);
    cout << i << ": " << m->GetID() << endl;
    m->View();
    cout << m->GetList()->size() << endl;
    m->PView();
    cout << m->GetPList()->size() << endl;
  }
}



This archive was generated by hypermail 2b29 : Thu Jan 01 2004 - 17:50:13 MET