Visual Computing Library  devel
Loading...
Searching...
No Matches
permute.h
1/*****************************************************************************
2 * VCLib *
3 * Visual Computing Library *
4 * *
5 * Copyright(C) 2021-2025 *
6 * Visual Computing Lab *
7 * ISTI - Italian National Research Council *
8 * *
9 * All rights reserved. *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the Mozilla Public License Version 2.0 as published *
13 * by the Mozilla Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19 * Mozilla Public License Version 2.0 *
20 * (https://www.mozilla.org/en-US/MPL/2.0/) for more details. *
21 ****************************************************************************/
22
23#ifndef VCL_BASE_PERMUTE_H
24#define VCL_BASE_PERMUTE_H
25
26#include <vclib/base/base.h>
27
28#include <vector>
29
30namespace vcl {
31
53template<typename T, typename... Args>
54void compactVector(
55 std::vector<T, Args...>& vec,
56 const std::vector<uint>& newIndices)
57{
58 assert(vec.size() == newIndices.size());
59 uint newSize = 0;
60 for (uint i = 0; i < newIndices.size(); ++i) {
61 if (newIndices[i] != UINT_NULL) {
62 ++newSize;
63 if (newIndices[i] != i) {
64 // must move the element from position i to position
65 // newIndices[i]
66 vec[newIndices[i]] = std::move(vec[i]);
67 }
68 }
69 }
70 vec.resize(newSize);
71}
72
109template<typename T, typename... Args>
110void permuteInPlace(
111 std::vector<T, Args...>& vec,
112 const std::vector<uint>& newIndices)
113{
114 using std::swap;
115
116 assert(vec.size() == newIndices.size());
117
118 std::vector<bool> visited(vec.size(), false);
119
120 for (uint i = 0; i < vec.size(); ++i) {
121 if (visited[i] || newIndices[i] == i) {
122 continue;
123 }
124
125 uint current = i;
126 T temp = std::move(vec[i]);
127
128 while (!visited[current]) {
129 visited[current] = true;
130 int next = newIndices[current];
131 swap(temp, vec[next]);
132 current = next;
133 }
134 }
135}
136
137} // namespace vcl
138
139#endif // VCL_BASE_PERMUTE_H
constexpr uint UINT_NULL
The UINT_NULL value represent a null value of uint that is the maximum value that can be represented ...
Definition base.h:48