std::ranges::search
Актуально для C++26.
#include <algorithm>
Актуально на 2025-06-03.
Define overload #1
template<forward_iterator I1, sentinel_for<I1> S1,
forward_iterator I2, sentinel_for<I2> S2,
class Pred = ranges::equal_to,
class Proj1 = identity,
class Proj2 = identity>
requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
constexpr subrange<I1>
search(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {},
Proj1 proj1 = {}, Proj2 proj2 = {});
Ищет в диапазоне [first1, last1] диапазон [first2, last2].
Example, possible implementation
Define overload #2
template<forward_range R1, forward_range R2,
class Pred = ranges::equal_to,
class Proj1 = identity,
class Proj2 = identity>
requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2>
constexpr borrowed_subrange_t<R1>
search(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {});
Ищет в диапазоне "r1" диапазон "r2".
Example, possible implementation
Возвращаемое значение
Вернёт ranges::subrange содержащий пару iterator-sentinel определяющих начало и конец найденного диапазона.
Если такового не нашлось, вернёт {last1, last1}.
Notes
- Во избежание возврата из функции итератора ссылающегося на временный объект, будет возвращен объект std::ranges::dangling, если "r" rvalue.
Сложность
Линейная = O(n).
Examples
Example 1:
#include <iostream>
#include <algorithm>
#include <string>
namespace ranges = std::ranges;
using namespace std::string_literals;
template<class T, class U>
constexpr auto
func(T&& haystack, U&& needle)
{
auto result = ranges::search(std::forward<T>(haystack), std::forward<T>(needle));
if constexpr(std::is_same_v<decltype(result), std::ranges::dangling>)
{
return "haystack is an rvalue?";
}
else
return result.empty() ?
"No matches." :
std::string_view{result.begin(), result.end()};
}
int main()
{
std::string str1 = "abcdefghijk";
std::string str2 = "def";
std::cout << func(str1, str2) << std::endl;
std::cout << func(std::move(str1), str2) << std::endl;
}
def t is an rvalue?
Changelog
C++20
Введён в стандарт.See also
TODO
This page was last modified on 2025-06-03