BRICKS
Small, useful blocks of code, to build bigger things.
Loading...
Searching...
No Matches
index_of.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <optional>
5#include <string>
6
8
9namespace bricks::detail {
10
14template <class Container,
15 typename std::enable_if_t<
16 std::negation_v<has_find<Container, typename Container::value_type>>, bool> = true>
17constexpr auto index_of(const Container& container,
18 const typename Container::value_type& value) noexcept
19 -> std::optional<std::size_t>
20{
21 const auto it = std::find(std::begin(container), std::end(container), value);
22 return it != std::end(container) ? std::make_optional(std::distance(std::begin(container), it))
23 : std::nullopt;
24}
25
29template <class Container, typename std::enable_if_t<
30 has_find_v<Container, typename Container::key_type>, bool> = true>
31constexpr auto index_of(const Container& container,
32 const typename Container::key_type& key) noexcept
33 -> std::optional<std::size_t>
34{
35 const auto it = container.find(key);
36 return it != std::end(container) ? std::make_optional(std::distance(std::begin(container), it))
37 : std::nullopt;
38}
39
43template <class CharT, class Traits = std::char_traits<CharT>,
44 class Allocator = std::allocator<CharT>>
45constexpr auto index_of(const std::basic_string<CharT, Traits, Allocator>& str,
46 const CharT& value) noexcept -> std::optional<std::size_t>
47{
48 const auto pos = str.find(value);
49 return pos != std::basic_string<CharT, Traits, Allocator>::npos ? std::make_optional(pos)
50 : std::nullopt;
51}
52
53} // namespace bricks::detail
constexpr auto index_of(const Container &container, const Value &value) noexcept -> std::optional< size_t >
Get the index of the first occurence of a value in a container.
Definition algorithm.hpp:136