How to use std::sort in pyroot

Hi all,

Sorry for bothering, but I did not find any information on the internet about this. This question is due to the fact that the sort method build in in python does another type of sorting then std::sort does.

Let’s say I would declare an vector

topo_list=vector('TString')()

or

topo_list=vector('string')()

Then how would one sort such an vector using std::sort. In C++ I would just call:

std::sort(topo_list.begin(),topo_list.end());

In pyroot, this is not equivalent to:

sort(topo_list.begin(),topo_list.end());

because that is non-functional for vectors. How would one import the std::sort in pyROOT? Any ideas are greatly appreciated.

Greetings,
Jelmer

Hi Jelmer,

you can sort using python instead of C++ algorithms. For example:

>>> topo_list=vector('TString')()
>>> topo_list.push_back("zz")
>>> topo_list.push_back("foo")
>>> topo_list.push_back("bar")
>>> topo_list.push_back("0000")
>>> topo_list
<ROOT.vector<TString> object at 0x3afd590>
>>> [ i for i in topo_list ] 
['zz', 'foo', 'bar', '0000']
>>> sorted_topo_list = sorted(topo_list)
>>> [ i for i in sorted_topo_list ] 
['0000', 'bar', 'foo', 'zz']

Cheers,
Danilo

Hi,

iterables can be sorted in python, and so that includes std.vector. Perhaps there may be some misunderstanding from the fact that the method in python is called ‘sorted’, not ‘sort’. So, do e.g. this:[code]>>> from ROOT import *

v = vector(‘TString’)()
v += [‘aap’, ‘noot’, ‘mies’, ‘zus’, ‘jet’]
print v
<ROOT.vector object at 0x3d33690>
print list(v)
[‘aap’, ‘noot’, ‘mies’, ‘zus’, ‘jet’]
sorted(v)
[‘aap’, ‘jet’, ‘mies’, ‘noot’, ‘zus’]
type(_)
<type ‘list’>
[/code]The only thing you may not like about it is that the result of sorted is a python list, not an std.vector, but that can’t be helped from a python builtin, of course.

Beyond that, you could instantiate a version of std::sort and use that as expected for an in-place sort (global template functions are currently not automatically instantiated).

Cheers,
Wim