Logo
Fully annotated reference manual - version 1.8.12
Loading...
Searching...
No Matches
vectorutils.hpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2016 Quaternion Risk Management Ltd
3 All rights reserved.
4
5 This file is part of ORE, a free-software/open-source library
6 for transparent pricing and risk analysis - http://opensourcerisk.org
7
8 ORE is free software: you can redistribute it and/or modify it
9 under the terms of the Modified BSD License. You should have received a
10 copy of the license along with this program.
11 The license is also available online at <http://opensourcerisk.org>
12
13 This program is distributed on the basis that it will form a useful
14 contribution to risk analytics and model standardisation, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
17*/
18
19/*! \file ored/utilities/vectorutils.hpp
20 \brief Utilities for sorting vectors using permutations
21 \ingroup utilities
22*/
23
24#pragma once
25
26#include <vector>
27
28namespace ore {
29namespace data {
30
31/*! Reference:
32 http://stackoverflow.com/questions/17074324/how-can-i-sort-two-vectors-in-the-same-way-with-criteria-that-uses-only-one-of
33 \addtogroup utilities
34 @{
35*/
36
37template <typename T, typename Compare>
38std::vector<std::size_t> sort_permutation(const std::vector<T>& vec, Compare& compare) {
39 std::vector<std::size_t> p(vec.size());
40 std::iota(p.begin(), p.end(), 0);
41 std::sort(p.begin(), p.end(), [&](std::size_t i, std::size_t j) { return compare(vec[i], vec[j]); });
42 return p;
43}
44
45template <typename T> std::vector<T> apply_permutation(const std::vector<T>& vec, const std::vector<std::size_t>& p) {
46 std::vector<T> sorted_vec(vec.size());
47 std::transform(p.begin(), p.end(), sorted_vec.begin(), [&](std::size_t i) { return vec[i]; });
48 return sorted_vec;
49}
50
51template <typename T> void apply_permutation_in_place(std::vector<T>& vec, const std::vector<std::size_t>& p) {
52 std::vector<bool> done(vec.size());
53 for (std::size_t i = 0; i < vec.size(); ++i) {
54 if (done[i])
55 continue;
56 done[i] = true;
57 for (std::size_t j = p[i]; i != j; j = p[j]) {
58 std::swap(vec[i], vec[j]);
59 done[j] = true;
60 }
61 }
62}
63
64//! @}
65} // namespace data
66} // namespace ore
std::vector< T > apply_permutation(const std::vector< T > &vec, const std::vector< std::size_t > &p)
Definition: vectorutils.hpp:45
void apply_permutation_in_place(std::vector< T > &vec, const std::vector< std::size_t > &p)
Definition: vectorutils.hpp:51
std::vector< std::size_t > sort_permutation(const std::vector< T > &vec, Compare &compare)
Definition: vectorutils.hpp:38
@ data
Definition: log.hpp:77
Serializable Credit Default Swap.
Definition: namespaces.docs:23