OR-Tools  9.6
flat_matrix.h
Go to the documentation of this file.
1 // Copyright 2010-2022 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #ifndef OR_TOOLS_UTIL_FLAT_MATRIX_H_
15 #define OR_TOOLS_UTIL_FLAT_MATRIX_H_
16 
17 // A very simple flattened 2D array of fixed size. It's movable, copyable.
18 // It can also be assigned.
19 // This was originally made to replace uses of vector<vector<...>> where each
20 // vector had a fixed size: vector<vector<>> has much worse performance in a
21 // highly concurrent setting, because it does a lot of memory allocations.
22 
23 #include <memory>
24 #include <vector>
25 
26 #include "absl/types/span.h"
27 
28 namespace operations_research {
29 
30 // NOTE(user): T=bool is not yet supported (the [] operator doesn't work).
31 template <typename T>
32 class FlatMatrix {
33  public:
34  FlatMatrix() : num_rows_(0), num_cols_(0) {}
35  FlatMatrix(size_t num_rows, size_t num_cols)
36  : num_rows_(num_rows),
37  num_cols_(num_cols),
38  array_(num_rows_ * num_cols_) {}
39  FlatMatrix(size_t num_rows, size_t num_cols, const T& elem)
40  : num_rows_(num_rows),
41  num_cols_(num_cols),
42  array_(num_rows_ * num_cols_, elem) {}
43 
44  size_t num_rows() const { return num_rows_; }
45  size_t num_cols() const { return num_cols_; }
46 
47  absl::Span<T> operator[](size_t row) {
48  return absl::Span<T>(array_.data() + row * num_cols_, num_cols_);
49  }
50  absl::Span<const T> operator[](size_t row) const {
51  return {array_.data() + row * num_cols_, num_cols_};
52  }
53 
54  private:
55  // Those are non-const only to support the assignment operators.
56  size_t num_rows_;
57  size_t num_cols_;
58  // NOTE(user): We could use a simpler unique_ptr<T[]> or even a self-managed
59  // memory block, but we'd need to define the copy constructor.
60  std::vector<T> array_;
61 };
62 
63 } // namespace operations_research
64 
65 #endif // OR_TOOLS_UTIL_FLAT_MATRIX_H_
absl::Span< const T > operator[](size_t row) const
Definition: flat_matrix.h:50
FlatMatrix(size_t num_rows, size_t num_cols, const T &elem)
Definition: flat_matrix.h:39
absl::Span< T > operator[](size_t row)
Definition: flat_matrix.h:47
FlatMatrix(size_t num_rows, size_t num_cols)
Definition: flat_matrix.h:35
RowIndex row
Definition: markowitz.cc:185
Collection of objects used to extend the Constraint Solver library.