WPILibC++ 2024.3.2
interpolating_map.h
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#pragma once
6
7#include <map>
8#include <utility>
9
10namespace wpi {
11
12/**
13 * Implements a table of key-value pairs with linear interpolation between
14 * values.
15 *
16 * If there's no matching key, the value returned will be a linear interpolation
17 * between the keys before and after the provided one.
18 *
19 * @tparam Key The key type.
20 * @tparam Value The value type.
21 */
22template <typename Key, typename Value>
24 public:
25 /**
26 * Inserts a key-value pair.
27 *
28 * @param key The key.
29 * @param value The value.
30 */
31 void insert(const Key& key, const Value& value) {
32 m_container.insert(std::make_pair(key, value));
33 }
34
35 /**
36 * Inserts a key-value pair.
37 *
38 * @param key The key.
39 * @param value The value.
40 */
41 void insert(Key&& key, Value&& value) {
42 m_container.insert(std::make_pair(key, value));
43 }
44
45 /**
46 * Returns the value associated with a given key.
47 *
48 * If there's no matching key, the value returned will be a linear
49 * interpolation between the keys before and after the provided one.
50 *
51 * @param key The key.
52 */
53 Value operator[](const Key& key) const {
54 using const_iterator = typename std::map<Key, Value>::const_iterator;
55
56 // Get iterator to upper bound key-value pair for the given key
57 const_iterator upper = m_container.upper_bound(key);
58
59 // If key > largest key in table, return value for largest table key
60 if (upper == m_container.end()) {
61 return (--upper)->second;
62 }
63
64 // If key <= smallest key in table, return value for smallest table key
65 if (upper == m_container.begin()) {
66 return upper->second;
67 }
68
69 // Get iterator to lower bound key-value pair
70 const_iterator lower = upper;
71 --lower;
72
73 // Perform linear interpolation between lower and upper bound
74 const double delta = (key - lower->first) / (upper->first - lower->first);
75 return delta * upper->second + (1.0 - delta) * lower->second;
76 }
77
78 /**
79 * Clears the contents.
80 */
81 void clear() { m_container.clear(); }
82
83 private:
84 std::map<Key, Value> m_container;
85};
86
87} // namespace wpi
Implements a table of key-value pairs with linear interpolation between values.
Definition: interpolating_map.h:23
void insert(Key &&key, Value &&value)
Inserts a key-value pair.
Definition: interpolating_map.h:41
void clear()
Clears the contents.
Definition: interpolating_map.h:81
void insert(const Key &key, const Value &value)
Inserts a key-value pair.
Definition: interpolating_map.h:31
Value operator[](const Key &key) const
Returns the value associated with a given key.
Definition: interpolating_map.h:53
Definition: ntcore_cpp.h:26