Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
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
14{
15 // Because RVec implements an iterator, the class is fully compatible with
16 // the sorting algorithms in the standard library.
17 ROOT::RVecD v1{6., 4., 5.};
19 std::sort(v2.begin(), v2.end());
20 std::cout << "Sort vector " << v1 << ": " << v2 << std::endl;
21
22 // For convenience, ROOT implements helpers, e.g., to get a sorted copy of
23 // an RVec ...
24 auto v3 = Sort(v1);
25 std::cout << "Sort vector " << v1 << ": " << v3 << std::endl;
26
27 // ... or a reversed copy of an RVec.
28 auto v4 = Reverse(v1);
29 std::cout << "Reverse vector " << v1 << ": " << v4 << std::endl;
30
31 // Helpers are provided to get the indices that sort the vector and to
32 // select these indices from an RVec.
33 auto i = Argsort(v1);
34 std::cout << "Indices that sort the vector " << v1 << ": " << i << std::endl;
35
36 ROOT::RVecD v5{9., 7., 8.};
37 auto v6 = Take(v5, i);
38 std::cout << "Sort vector " << v5 << " respective to the previously"
39 << " determined indices: " << v6 << std::endl;
40
41 // Take can also be used to get the first or last elements of an RVec.
42 auto v7 = Take(v1, 2);
43 auto v8 = Take(v1, -2);
44 std::cout << "Take the two first and last elements of vector " << v1
45 << ": " << v7 << ", " << v8 << std::endl;
46
47 // Because the helpers return a copy of the input, you can chain the operations
48 // conveniently.
49 auto v9 = Reverse(Take(Sort(v1), -2));
50 std::cout << "Sort the vector " << v1 << ", take the two last elements and "
51 << "reverse the selection: " << v9 << std::endl;
52}
RVec< T > Reverse(const RVec< T > &v)
Return copy of reversed vector.
Definition RVec.hxx:2444
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:2302
RVec< typename RVec< T >::size_type > Argsort(const RVec< T > &v)
Return an RVec of indices that sort the input RVec.
Definition RVec.hxx:2213
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Sort the n elements of the array a of generic templated type Element.
Definition TMathBase.h:431