Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TListAndSTL.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_cont_legacy
3/// \notebook -nodraw
4/// This is an example of using TList with STL algoritms in CLING.
5///
6/// #### Output produced by `.x TListAndSTL.C`
7/// \macro_output
8///
9/// #### `TListAndSTL.C` code
10/// \macro_code
11///
12/// \author Anar Manafov
13
14// STD
15#include <algorithm>
16#include <iostream>
17#include <sstream>
18
19// ROOT
20#include "TList.h"
21#include "TCollection.h"
22#include "TObjString.h"
23
24// A functor for the for_each algorithm
25struct SEnumFunctor {
26 bool operator()(TObject *aObj) {
27 if (!aObj)
28 return false;
29
30 TObjString *str(dynamic_cast<TObjString*>(aObj));
31 if (!str)
32 return false;
33
34 cout << "Value: " << str->String().Data() << endl;
35 return true;
36 }
37};
38
39// A functor for the find_if algorithm
40struct SFind {
41 // using this ugly constructor, since there is problems with std::bindX in CINT
42
43 SFind(const TString &aStr): fToFind(aStr) {
44
45 }
46 bool operator()(TObject *aObj) {
47 TObjString *str(dynamic_cast<TObjString*>(aObj));
48 return !str->String().CompareTo(fToFind);
49 }
50private:
51 const TString fToFind;
52};
53
54
55// The "main" function
56void TListAndSTL()
57{
58 const Int_t size(10);
59
60 // Initializing TList container
61 TList stringList;
62 ostringstream ss;
63 for (int i = 0; i < size; ++i) {
64 ss << "test string #" << i;
65 TObjString *s(new TObjString(ss.str().c_str()));
66 stringList.Add(s);
67 ss.str("");
68 }
69
70
71 // ### Example #1
72 // Running the std::for_each algorithm on the list
73 for_each(stringList.begin(), stringList.end(), SEnumFunctor());
74
75 // ### Example #2
76 // We can try to find something in the container
77 // using the std::find_if algorithm on the list
78 string strToFind("test string #4");
79 SFind func(strToFind.c_str());
80
81 TIterCategory<TList> iter_cat(&stringList);
83 = find_if(iter_cat.Begin(), TIterCategory<TList>::End(), func);
84
85 // Checking the result
86 if (!(*found)) {
87 cerr << "Can't find the string: \"" << strToFind << "\" in the container" << endl;
88 return;
89 }
90
91 TObjString *str(dynamic_cast<TObjString*>(*found));
92 if (!str) {
93 cerr << "Can't find the string: \"" << strToFind << "\" in the container" << endl;
94 return;
95 }
96
97 cout << "The string has been found: " << str->String().Data() << endl;
98}
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
int Int_t
Definition RtypesCore.h:45
TRObject operator()(const T1 &t1) const
TIter end() const
TIter begin() const
A doubly linked list.
Definition TList.h:38
void Add(TObject *obj) override
Definition TList.h:81
Collectable string class.
Definition TObjString.h:28
Mother of all ROOT objects.
Definition TObject.h:41
Basic string class.
Definition TString.h:139