 ROOT   Reference Guide vo004_SortAndSelect.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_vecops
3/// \notebook -nodraw
4/// In this tutorial we learn how elements of an RVec can be easily sorted and
5/// selected.
6///
7/// \macro_code
8/// \macro_output
9///
10/// \date August 2018
11/// \author Stefan Wunsch
12
13using namespace ROOT::VecOps;
14
16{
17 // Because RVec implements an iterator, the class is fully compatible with
18 // the sorting algorithms in the standard library.
19 RVec<double> v1{6., 4., 5.};
21 std::sort(v2.begin(), v2.end());
22 std::cout << "Sort vector " << v1 << ": " << v2 << std::endl;
23
24 // For convenience, ROOT implements helpers, e.g., to get a sorted copy of
25 // an RVec ...
26 auto v3 = Sort(v1);
27 std::cout << "Sort vector " << v1 << ": " << v3 << std::endl;
28
29 // ... or a reversed copy of an RVec.
30 auto v4 = Reverse(v1);
31 std::cout << "Reverse vector " << v1 << ": " << v4 << std::endl;
32
33 // Helpers are provided to get the indices that sort the vector and to
34 // select these indices from an RVec.
35 auto i = Argsort(v1);
36 std::cout << "Indices that sort the vector " << v1 << ": " << i << std::endl;
37
38 RVec<double> v5{9., 7., 8.};
39 auto v6 = Take(v5, i);
40 std::cout << "Sort vector " << v5 << " respective to the previously"
41 << " determined indices: " << v6 << std::endl;
42
43 // Take can also be used to get the first or last elements of an RVec.
44 auto v7 = Take(v1, 2);
45 auto v8 = Take(v1, -2);
46 std::cout << "Take the two first and last elements of vector " << v1
47 << ": " << v7 << ", " << v8 << std::endl;
48
49 // Because the helpers return a copy of the input, you can chain the operations
50 // conveniently.
51 auto v9 = Reverse(Take(Sort(v1), -2));
52 std::cout << "Sort the vector " << v1 << ", take the two last elements and "
53 << "reverse the selection: " << v9 << std::endl;
54}
RVec< T > Reverse(const RVec< T > &v)
Return copy of reversed vector.
Definition: RVec.hxx:1116
RVec< T > Take(const RVec< T > &v, const RVec< typename RVec< T >::size_type > &i)
Return elements of a vector at given indices.
Definition: RVec.hxx:1058
RVec< typename RVec< T >::size_type > Argsort(const RVec< T > &v)
Return an RVec of indices that sort the input RVec.
Definition: RVec.hxx:1038
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Definition: TMathBase.h:362