coveo::linq
Implementation of .NET-like LINQ operators in C++
Functions

Returns the only element in a sequence. More...

Functions

template<typename = void>
auto coveo::linq::single () -> detail::single_impl_0<>
 Returns only element in sequence. More...
 
template<typename Pred >
auto coveo::linq::single (const Pred &pred) -> detail::single_impl_1< Pred >
 Returns only element in sequence satisfying predicate. More...
 

Detailed Description

The single operator returns the only element in a sequence, or the only element to satisfy a predicate. If the sequence does not have such an element or has more than one of them, an exception is thrown.

This is a terminal operator.

.NET equivalent: Single

Function Documentation

◆ single() [1/2]

template<typename = void>
auto coveo::linq::single ( ) -> detail::single_impl_0<>

Returns the only element in a sequence. If the sequence does not have elements or has more than one element, an exception is thrown.

Use like this:

const std::vector<int> YES = { 42 };
const std::vector<int> NAY1;
const std::vector<int> NAY2 = { 42, 23, 66 };
using namespace coveo::linq;
auto val1 = from(YES)
| single();
// val1 == 42
// This throws an exception:
// auto val2 = from(NAY1)
// | single();
// This also throws an exception:
// auto val3 = from(NAY2)
// | single();
Returns
(Once applied) Only element in sequence.
Exceptions
coveo::linq::empty_sequenceThe sequence does not have elements.
coveo::linq::out_of_rangeThe sequence has more than one element.

◆ single() [2/2]

template<typename Pred >
auto coveo::linq::single ( const Pred &  pred) -> detail::single_impl_1<Pred>

Returns the only element in a sequence that satisfy the given predicate. If no element in the sequence or if more than one element in the sequence satisfy the predicate, an exception is thrown.

Use like this:

const std::vector<int> YES = { 42, 23, 66 };
const std::vector<int> NAY1 = { 67, 11, 7 };
const std::vector<int> NAY2 = { 42, 24, 66 };
auto is_odd = [](int i) { return i % 2 != 0; };
using namespace coveo::linq;
auto val1 = from(YES)
| single(is_odd);
// val1 == 23
// This throws an exception:
// auto val2 = from(NAY1)
// | single(is_odd);
// This also throws an exception:
// auto val3 = from(NAY2)
// | single(is_odd);
Parameters
predPredicate to satisfy.
Returns
(Once applied) Only element in sequence for which pred returned true.
Exceptions
coveo::linq::empty_sequenceThe sequence does not have elements.
coveo::linq::out_of_rangeNo element satisfy pred, or more than one element satisfy pred.