Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/search"

From cppreference.com
< cpp‎ | algorithm
(Complexity wording update.)
(Added LWG issue #1338 DR.)
Line 194: Line 194:
 
===Defect reports===
 
===Defect reports===
 
{{dr list begin}}
 
{{dr list begin}}
{{dr list item|wg=lwg|dr=1205|std=C++98|before=the return value was unclear if {{range|s_first|s_last}} is empty|after=returns {{c|last}} in this case}}
+
{{dr list item|wg=lwg|dr=1205|std=C++98|before=the return value was unclear if {{range|s_first|s_last}} is empty|after=returns {{c|first}} in this case}}
 +
{{dr list item|wg=lwg|dr=1338|std=C++98|before=the resolution of {{lwg|1205}} was incorrectly applied,<br>making {{c|first}} to be returned if no occurence is found|after=returns {{c|last}} in this case}}
 
{{dr list end}}
 
{{dr list end}}
  

Revision as of 18:38, 3 August 2023

 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy, ranges::sort, ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
(C++11)                (C++11)(C++11)

Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17)(C++11)
(C++20)(C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
 
Defined in header <algorithm>
(1)
template< class ForwardIt1, class ForwardIt2 >

ForwardIt1 search( ForwardIt1 first, ForwardIt1 last,

                   ForwardIt2 s_first, ForwardIt2 s_last );
(until C++20)
template< class ForwardIt1, class ForwardIt2 >

constexpr ForwardIt1 search( ForwardIt1 first, ForwardIt1 last,

                             ForwardIt2 s_first, ForwardIt2 s_last );
(since C++20)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >

ForwardIt1 search( ExecutionPolicy&& policy,
                   ForwardIt1 first, ForwardIt1 last,

                   ForwardIt2 s_first, ForwardIt2 s_last );
(2) (since C++17)
(3)
template< class ForwardIt1, class ForwardIt2, class BinaryPredicate >

ForwardIt1 search( ForwardIt1 first, ForwardIt1 last,
                   ForwardIt2 s_first, ForwardIt2 s_last,

                   BinaryPredicate p );
(until C++20)
template< class ForwardIt1, class ForwardIt2, class BinaryPredicate >

constexpr ForwardIt1 search( ForwardIt1 first, ForwardIt1 last,
                             ForwardIt2 s_first, ForwardIt2 s_last,

                             BinaryPredicate p );
(since C++20)
template< class ExecutionPolicy,

          class ForwardIt1, class ForwardIt2, class BinaryPredicate >
ForwardIt1 search( ExecutionPolicy&& policy,
                   ForwardIt1 first, ForwardIt1 last,
                   ForwardIt2 s_first, ForwardIt2 s_last,

                   BinaryPredicate p );
(4) (since C++17)
(5)
template< class ForwardIt, class Searcher >

ForwardIt search( ForwardIt first, ForwardIt last,

                  const Searcher& searcher );
(since C++17)
(until C++20)
template< class ForwardIt, class Searcher >

constexpr ForwardIt search( ForwardIt first, ForwardIt last,

                            const Searcher& searcher );
(since C++20)
1-4) Searches for the first occurrence of the sequence of elements [s_firsts_last) in the range [firstlast).
1) Elements are compared using operator==.
3) Elements are compared using the given binary predicate p.
2,4) Same as (1,3), but executed according to policy. These overloads participate in overload resolution only if

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> is true.

(until C++20)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> is true.

(since C++20)
5) Searches the range [firstlast) for the pattern specified in the constructor of searcher. Searcher need not be CopyConstructible.

The standard library provides the following searchers:

standard C++ library search algorithm implementation
(class template) [edit]
Boyer-Moore search algorithm implementation
(class template) [edit]
Boyer-Moore-Horspool search algorithm implementation
(class template) [edit]
(since C++17)

Contents

Parameters

first, last - the range of elements to examine
s_first, s_last - the range of elements to search for
policy - the execution policy to use. See execution policy for details.
searcher - the searcher encapsulating the search algorithm and the pattern to look for
p - binary predicate which returns ​true if the elements should be treated as equal.

The signature of the predicate function should be equivalent to the following:

 bool pred(const Type1 &a, const Type2 &b);

While the signature does not need to have const &, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value category (thus, Type1 & is not allowed, nor is Type1 unless for Type1 a move is equivalent to a copy(since C++11)).
The types Type1 and Type2 must be such that objects of types ForwardIt1 and ForwardIt2 can be dereferenced and then implicitly converted to Type1 and Type2 respectively. ​

Type requirements
-
ForwardIt1, ForwardIt2 must meet the requirements of LegacyForwardIterator.

Return value

1-4) Iterator to the beginning of first occurrence of the sequence [s_firsts_last) in the range [firstlast). If no such occurrence is found, last is returned.
If [s_firsts_last) is empty, first is returned.
5) searcher(first, last).first.

Complexity

1-4) Given N as std::distance(first, last) and S as std::distance(s_first, s_last):
1,2) At most N·S comparisons using operator==.
3,4) At most N·S applications of the predicate p.
5) Depends on searcher.

Exceptions

The overloads with a template parameter named ExecutionPolicy report errors as follows:

  • If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies, std::terminate is called. For any other ExecutionPolicy, the behavior is implementation-defined.
  • If the algorithm fails to allocate memory, std::bad_alloc is thrown.

Possible implementation

search (1)
template<class ForwardIt1, class ForwardIt2>
constexpr ForwardIt1 search(ForwardIt1 first, ForwardIt1 last,
                            ForwardIt2 s_first, ForwardIt2 s_last)
{
    while (true)
    {
        ForwardIt1 it = first;
        for (ForwardIt2 s_it = s_first; ; ++it, ++s_it)
        {
            if (s_it == s_last)
                return first;
            if (it == last)
                return last;
            if (!(*it == *s_it))
                break;
        }
        ++first;
    }
}
search (3)
template<class ForwardIt1, class ForwardIt2, class BinaryPredicate>
constexpr ForwardIt1 search(ForwardIt1 first, ForwardIt1 last,
                            ForwardIt2 s_first, ForwardIt2 s_last,
                            BinaryPredicate p)
{
    while (true)
    {
        ForwardIt1 it = first;
        for (ForwardIt2 s_it = s_first; ; ++it, ++s_it)
        {
            if (s_it == s_last)
                return first;
            if (it == last)
                return last;
            if (!p(*it, *s_it))
                break;
        }
        ++first;
    }
}

Example

#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string_view>
#include <vector>
 
using namespace std::literals;
 
bool contains(const auto& cont, std::string_view s)
{
    // str.find() (or str.contains(), since C++23) can be used as well
    return std::search(cont.begin(), cont.end(), s.begin(), s.end()) != cont.end();
}
 
int main()
{
    const auto str{"why waste time learning, when ignorance is instantaneous?"sv};
 
    std::cout << std::boolalpha
              << contains(str, "learning") << '\n'  // true
              << contains(str, "lemming")  << '\n'; // false
 
    const std::vector vec(str.begin(), str.end());
    std::cout << contains(vec, "learning") << '\n'  // true
              << contains(vec, "leaning")  << '\n'; // false
 
    // The C++17 overload with searchers demo:
    constexpr auto haystack
    {
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed "
        "do eiusmod tempor incididunt ut labore et dolore magna aliqua"sv
    };
 
    for (const auto needle : {"pisci"sv, "Pisci"sv})
    {
        const std::boyer_moore_searcher searcher(needle.begin(), needle.end());
        const auto it = std::search(haystack.begin(), haystack.end(), searcher);
        std::cout << "The string " << std::quoted(needle) << ' ';
        if (it == haystack.end())
            std::cout << "not found\n";
        else
            std::cout << "found at offset " << it - haystack.begin() << '\n';
    }
}

Output:

true
false
true
false
The string "pisci" found at offset 43
The string "Pisci" not found

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 1205 C++98 the return value was unclear if [s_firsts_last) is empty returns first in this case
LWG 1338 C++98 the resolution of LWG issue 1205 was incorrectly applied,
making first to be returned if no occurence is found
returns last in this case

See also

finds the last sequence of elements in a certain range
(function template) [edit]
returns true if one sequence is a subsequence of another
(function template) [edit]
determines if two sets of elements are the same
(function template) [edit]
finds the first element satisfying specific criteria
(function template) [edit]
returns true if one range is lexicographically less than another
(function template) [edit]
finds the first position where two ranges differ
(function template) [edit]
searches for the first occurrence of a number consecutive copies of an element in a range
(function template) [edit]
standard C++ library search algorithm implementation
(class template) [edit]
Boyer-Moore search algorithm implementation
(class template) [edit]
Boyer-Moore-Horspool search algorithm implementation
(class template) [edit]
searches for the first occurrence of a range of elements
(niebloid)[edit]