# T List And S T L¶

This is an example of using TList with STL algoritms in CLING.

#### TListAndSTL.C code¶

Author: Anar Manafov
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Wednesday, August 04, 2021 at 12:00 PM.

Std

In [1]:
%%cpp -d
#include <algorithm>
#include <iostream>
#include <sstream>

Root

In [2]:
%%cpp -d
#include "TList.h"
#include "TCollection.h"
#include "TObjString.h"

A functor for the for_each algorithm

In [3]:
struct SEnumFunctor {
bool operator()(TObject *aObj) {
if (!aObj)
return false;

TObjString *str(dynamic_cast<TObjString*>(aObj));
if (!str)
return false;

cout << "Value: " << str->String().Data() << endl;
return true;
}
};

A functor for the find_if algorithm

In [4]:
struct SFind {
// using this ugly constructor, since there is problems with std::bindX in CINT

SFind(const TString &aStr): fToFind(aStr) {

}
bool operator()(TObject *aObj) {
TObjString *str(dynamic_cast<TObjString*>(aObj));
return !str->String().CompareTo(fToFind);
}
private:
const TString fToFind;
};

The "main" function

In [5]:
const Int_t size(10);

Initializing tlist container

In [6]:
TList stringList;
ostringstream ss;
for (int i = 0; i < size; ++i) {
ss << "test string #" << i;
TObjString *s(new TObjString(ss.str().c_str()));
ss.str("");
}

### Example #1¶

Running the std::for_each algorithm on the list

In [7]:
for_each(stringList.begin(), stringList.end(), SEnumFunctor());
Value: test string #0
Value: test string #1
Value: test string #2
Value: test string #3
Value: test string #4
Value: test string #5
Value: test string #6
Value: test string #7
Value: test string #8
Value: test string #9

### Example #2¶

We can try to find something in the container using the std::find_if algorithm on the list

In [8]:
string strToFind("test string #4");
SFind func(strToFind.c_str());

TIterCategory<TList> iter_cat(&stringList);
TIterCategory<TList> found
= find_if(iter_cat.Begin(), TIterCategory<TList>::End(), func);

Checking the result

In [9]:
if (!(*found)) {
cerr << "Can't find the string: \"" << strToFind << "\" in the container" << endl;
return;
}

TObjString *str(dynamic_cast<TObjString*>(*found));
if (!str) {
cerr << "Can't find the string: \"" << strToFind << "\" in the container" << endl;
return;
}

cout << "The string has been found: " << str->String().Data() << endl;
The string has been found: test string #4