Namespaces
Variants

std::ranges::contains, std::ranges::contains_subrange

Depuis fr.cppreference.net
 
 
Bibliothèque d’algorithmes
Algorithmes contraints et algorithmes sur ranges (C++20)
Algorithmes contraints, p. ex. ranges::copy, ranges::sort, ...
Opérations de séquence non modificatrices    
Opérations par lots
(C++17)
Opérations de recherche
Opérations de séquence modificatrices
Opérations de copie
(C++11)
(C++11)
Opérations d’échange
Opérations de transformation
Opérations de génération
Opérations de suppression
Opérations de changement d’ordre
(jusqu’à C++17)(C++11)
(C++20)(C++20)
Opérations d’échantillonnage
(C++17)

Tri et opérations connexes
Opérations de partitionnement
(C++11)    

Opérations de tri
Opérations de recherche dichotomique
(sur des ranges partitionnés)
Opérations d’ensemble (sur des ranges triés)
Opérations de fusion (sur des ranges triés)
Opérations de tas
Opérations min/max
(C++11)
(C++17)
Opérations de comparaison lexicographique
Opérations de permutation


 
Algorithmes contraints
Tous les noms de ce menu appartiennent à l’espace de noms std::ranges
Opérations de séquence non modificatrices
Opérations de séquence modificatrices
Opérations de partitionnement
Opérations de tri
Opérations de recherche dichotomique (sur des ranges triés)
       
       
Opérations d’ensemble (sur des ranges triés)
Opérations de tas
Opérations min/max
       
       
Opérations de permutation
Opérations de pliage
Opérations sur la mémoire non initialisée
Types de retour
 
Défini dans l’en‑tête <algorithm>
Signature d’appel
template< std::input_iterator I, std::sentinel_for<I> S,
          class T,
          class Proj = std::identity >
    requires std::indirect_binary_predicate
                 <ranges::equal_to, std::projected<I, Proj>, const T*>
constexpr bool contains( I first, S last, const T& value, Proj proj = {} );
(1) (depuis C++23)
(jusqu’à C++26)
template< std::input_iterator I, std::sentinel_for<I> S,
          class Proj = std::identity,
          class T = std::projected_value_t<I, Proj> >
    requires std::indirect_binary_predicate
                 <ranges::equal_to, std::projected<I, Proj>, const T*>
constexpr bool contains( I first, S last, const T& value, Proj proj = {} );
(depuis C++26)
template< ranges::input_range R,
          class T,
          class Proj = std::identity >
    requires std::indirect_binary_predicate
                 <ranges::equal_to,
                  std::projected<ranges::iterator_t<R>, Proj>, const T*>
constexpr bool contains( R&& r, const T& value, Proj proj = {} );
(2) (depuis C++23)
(jusqu’à C++26)
template< ranges::input_range R,
          class Proj = std::identity,
          class T = std::projected_value_t<ranges::iterator_t<R>, Proj> >
    requires std::indirect_binary_predicate
                 <ranges::equal_to,
                  std::projected<ranges::iterator_t<R>, Proj>, const T*>
constexpr bool contains( R&& r, const T& value, Proj proj = {} );
(depuis C++26)
template< std::forward_iterator I1, std::sentinel_for<I1> S1,
          std::forward_iterator I2, std::sentinel_for<I2> S2,
          class Pred = ranges::equal_to,
          class Proj1 = std::identity, class Proj2 = std::identity >
    requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
constexpr bool contains_subrange( I1 first1, S1 last1, I2 first2, S2 last2,
                                  Pred pred = {},
                                  Proj1 proj1 = {}, Proj2 proj2 = {} );
(3) (depuis C++23)
template< ranges::forward_range R1, ranges::forward_range R2,
          class Pred = ranges::equal_to,
          class Proj1 = std::identity, class Proj2 = std::identity >
    requires std::indirectly_comparable
                 <ranges::iterator_t<R1>, ranges::iterator_t<R2>,
                  Pred, Proj1, Proj2>
constexpr bool contains_subrange( R1&& r1, R2&& r2, Pred pred = {},
                                  Proj1 proj1 = {}, Proj2 proj2 = {} );
(4) (depuis C++23)
template< /*execution-policy*/ Ep,
          std::random_access_iterator I, std::sized_sentinel_for<I> S,
          class Proj = std::identity,
          class T = std::projected_value_t<I, Proj> >
    requires std::indirect_binary_predicate
                 <ranges::equal_to, std::projected<I, Proj>, const T*>
bool contains( Ep&& policy, I first, S last, const T& value, Proj proj = {} );
(5) (depuis C++26)
template< /*execution-policy*/ Ep, /*sized-random-access-range*/ R,
          class Proj = std::identity,
          class T = std::projected_value_t<ranges::iterator_t<R>, Proj> >
    requires std::indirect_binary_predicate
                 <ranges::equal_to,
                  std::projected<ranges::iterator_t<R>, Proj>, const T*>
bool contains( Ep&& policy, R&& r, const T& value, Proj proj = {} );
(6) (depuis C++26)
template< /*execution-policy*/ Ep,
          std::random_access_iterator I1, std::sized_sentinel_for<I1> S1,
          std::random_access_iterator I2, std::sized_sentinel_for<I2> S2,
          class Pred = ranges::equal_to,
          class Proj1 = std::identity, class Proj2 = std::identity >
    requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
bool contains_subrange( Ep&& policy, I1 first1, S1 last1, I2 first2, S2 last2,
                        Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} );
(7) (depuis C++26)
template< /*execution-policy*/ Ep,
          /*sized-random-access-range*/ R1, /*sized-random-access-range*/ R2,
          class Pred = ranges::equal_to,
          class Proj1 = std::identity, class Proj2 = std::identity >
    requires std::indirectly_comparable
                 <ranges::iterator_t<R1>, ranges::iterator_t<R2>,
                  Pred, Proj1, Proj2>
bool contains_subrange( Ep&& policy, R1&& r1, R2&& r2, Pred pred = {},
                        Proj1 proj1 = {}, Proj2 proj2 = {} );
(8) (depuis C++26)

Pour la définition de /*execution-policy*/, voir cette page ; pour la définition de /*sized-random-access-range*/, voir cette page.

1,2) Vérifie si le range source contient la valeur cible value.
1) Le range source est [firstlast).
2) Le range source est r.
3,4) Vérifie si le range cible est un sous‑range du range source.
3) Le range source est [first1last1), et le range cible est [first2last2).
4) Le range source est r1, et le range cible est r2.
5-8) Identique à (1-4), mais exécuté selon policy.

Les entités de type fonction décrites sur cette page sont des objets fonctions algorithmiques (informellement appelés niebloïdes), c’est‑à‑dire :

Paramètres

first/first1, last/last1 - la paire itérateur‑sentinelle définissant le range
sourcefirst2, last2 - la paire itérateur‑sentinelle définissant le range
cibler/r1 - le range source
value - la valeur cible
r2 - le range cible
pred/pred1 - le prédicat à appliquer aux éléments (projetés) du range source
pred2 - le prédicat à appliquer aux éléments (projetés) du range cible
proj/proj1 - la projection à appliquer aux éléments du range source
proj2 - la projection à appliquer aux éléments du range cible
policy - la politique d’exécution à utiliser

Valeur de retour

1) ranges::find(std::move(first), last, value, proj) != last
2) ranges::find(r, value, proj) != ranges::end(r)
3) first2 == last2 || !ranges::search(first1, last1, first2, last2, pred, proj1, proj2).empty()
4) ranges::empty(r2) || !ranges::search(r1, r2, pred, proj1, proj2).empty()
5-8) Identique à (1-4), mais insère std::forward<Ep>(policy) dans la liste d’arguments de ranges::find ou ranges::search comme premier argument.

Complexité

Étant donné

  • N comme ranges::distance(first, last) ou ranges::distance(r),
  • N1 comme ranges::distance(first1, last1) ou ranges::distance(r1), et
  • N2 comme ranges::distance(first2, last2) ou ranges::distance(r2) :
1,2) Au plus N comparaisons et applications de proj.
3,4) Au plus N1·N2 applications de pred et proj.
5,6) 𝓞(N) comparaisons et applications de proj.
7,8) 𝓞(N1·N2) applications de pred et proj.

Exceptions

5-8) Pendant le processus d’exécution :
  • Si les ressources mémoire temporaires nécessaires à la parallélisation ne sont pas disponibles, std::bad_alloc est levée.
  • Si une exception non rattrapée est levée lors de l’accès aux objets via un argument d’algorithme, le comportement est déterminé par la politique d’exécution (pour les politiques standard, std::terminate est appelé).

Notes

En C++20, on peut implémenter contains avec ranges::find(haystack, needle) != ranges::end(haystack) ou contains_subrange avec !ranges::search(haystack, needle).empty().

ranges::contains_subrange, comme ranges::search, et contrairement à std::search, ne supporte pas les chercheurs (tels que std::boyer_moore_searcher).

Macro de test de fonctionnalité Valeur Std Fonctionnalité
__cpp_lib_ranges_contains 202207L (C++23) ranges::contains et ranges::contains_subrange
__cpp_lib_algorithm_default_value_type 202403L (C++26) Initialisation par liste pour les algorithmes (1,2)

Implémentation possible

contains (1,2)
struct contains_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity,
             class T = std::projected_value_t<I, Proj>>
    requires std::indirect_binary_predicate
                 <ranges::equal_to, std::projected<I, Proj>, const T*>
    constexpr bool operator()(I first, S last, const T& value, Proj proj = {}) const
    {
        return ranges::find(std::move(first), last, value, proj) != last;
    }
    
    template<ranges::input_range R,
             class Proj = std::identity,
             class T = std::projected_value_t<ranges::iterator_t<R>, Proj>>
    requires std::indirect_binary_predicate
                 <ranges::equal_to,
                  std::projected<ranges::iterator_t<R>, Proj>, const T*>
    constexpr bool operator()(R&& r, const T& value, Proj proj = {}) const
    {
        return ranges::find(r, value, proj) != ranges::end(r);
    }
};

inline constexpr contains_fn contains{};
contains_subrange (3,4)
struct contains_subrange_fn
{
    template<std::forward_iterator I1, std::sentinel_for<I1> S1,
             std::forward_iterator I2, std::sentinel_for<I2> S2,
             class Pred = ranges::equal_to,
             class Proj1 = std::identity, class Proj2 = std::identity>
    requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
    constexpr bool operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {},
                              Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        return (first2 == last2) ||
                   !ranges::search(first1, last1, first2, last2,
                                   pred, proj1, proj2).empty();
    }
    
    template<ranges::forward_range R1, ranges::forward_range R2,
             class Pred = ranges::equal_to,
             class Proj1 = std::identity, class Proj2 = std::identity>
    requires std::indirectly_comparable<ranges::iterator_t<R1>,
                                        ranges::iterator_t<R2>, Pred, Proj1, Proj2>
    constexpr bool operator()(R1&& r1, R2&& r2, Pred pred = {},
                              Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        return ranges::empty(r2) ||
                   !ranges::search(r1, r2, pred, proj1, proj2).empty();
    }
};

inline constexpr contains_subrange_fn contains_subrange{};

Exemple

#include <algorithm>
#include <array>
#include <complex>

namespace ranges = std::ranges;

int main()
{
    constexpr auto haystack = std::array{3, 1, 4, 1, 5};
    constexpr auto needle = std::array{1, 4, 1};
    constexpr auto bodkin = std::array{2, 5, 2};
    
    static_assert
    (
        ranges::contains(haystack, 4) &&
       !ranges::contains(haystack, 6) &&
        ranges::contains_subrange(haystack, needle) &&
       !ranges::contains_subrange(haystack, bodkin)
    );
    
    constexpr std::array<std::complex<double>, 3> nums{{{1, 2}, {3, 4}, {5, 6}}};
    #ifdef __cpp_lib_algorithm_default_value_type
        static_assert(ranges::contains(nums, {3, 4}));
    #else
        static_assert(ranges::contains(nums, std::complex<double>{3, 4}));
    #endif
}

Voir aussi

trouve le premier élément satisfaisant des critères spécifiques
(objet fonction algorithmique)
recherche la première occurrence d’un range d’éléments
(objet fonction algorithmique)
détermine si un élément existe dans un range en utilisant une recherche dichotomique
(objet fonction algorithmique)
détermine si une séquence est une sous‑séquence d’une autre
(objet fonction algorithmique)
vérifie si un prédicat est true vrai pour tous, au moins un ou aucun des éléments d’un range
(objet fonction algorithmique)