qxLib
add.h
Go to the documentation of this file.
1 /**
2 
3  @file add.h
4  @author Khrapov
5  @date 14.08.2022
6  @copyright © Nick Khrapov, 2022. All right reserved.
7 
8 **/
9 #pragma once
10 
11 #include <qx/algo/contains.h>
12 
13 #include <type_traits>
14 
15 namespace qx
16 {
17 
18 /**
19  @brief Add an element to the container if it doesn't already contain one
20  @tparam container_t - container type
21  @tparam value_t - value type
22  @param container - container to add to
23  @param value - value to check and add
24  @retval - true if value was added
25 **/
26 template<class container_t, class value_t>
27 bool add_unique(container_t& container, value_t&& value)
28 {
29  if (!contains(container, value))
30  {
31  container.insert(container.end(), std::forward<value_t>(value));
32  return true;
33  }
34  else
35  {
36  return false;
37  }
38 }
39 
40 /**
41  @brief Add an element to the container if all elements do not satisfy the predicate
42  @tparam container_t - container type
43  @tparam value_t - value type
44  @tparam predicate_t - predicate type which can be called with (element, value) or (element) only
45  @param container - container to add to
46  @param value - value to check and add
47  @param predicate - predicate object
48  @retval - true if value was added
49 **/
50 template<class container_t, class value_t, class predicate_t>
51 bool add_unique_if(container_t& container, value_t&& value, const predicate_t& predicate)
52 {
53  for (const auto& element : container)
54  {
55  if constexpr (std::is_invocable_v<predicate_t, decltype(element), const value_t&>)
56  {
57  if (predicate(element, value))
58  return false;
59  }
60  else
61  {
62  if (predicate(element))
63  return false;
64  }
65  }
66 
67  container.insert(container.end(), std::forward<value_t>(value));
68  return true;
69 }
70 
71 } // namespace qx
bool add_unique(container_t &container, value_t &&value)
Add an element to the container if it doesn't already contain one.
Definition: add.h:27
bool add_unique_if(container_t &container, value_t &&value, const predicate_t &predicate)
Add an element to the container if all elements do not satisfy the predicate.
Definition: add.h:51
Check that tuple type contains T.