Element Operators - cemderv/linq GitHub Wiki

element_at()

Returns the element at a given index in the range.

Signature:

std::optional<T> element_at(size_t index) const;

Example:

const vector numbers { 1, 2, 3, 4 };

optional<int> num1 = linq::from(&numbers).element_at(2);
optional<int> num2 = linq::from(&numbers).element_at(6); // access to non-existent element
                                                              // will return an empty optional

println("{}", num1.value_or(0));
println("{}", num2.value_or(0));

Output:

3
0

first()

Returns the first element of the range, or the first element that fulfills a given predicate.

Signature:

std::optional<output_t> first() const;

template <typename TPredicate>
std::optional<output_t> first(const TPredicate& predicate) const;

Example:

const vector numbers { 1, 2, 3, 4 };

optional<int> num1 = linq::from(&numbers)
                               .first();

optional<int> num2 = linq::from(&numbers)
                               .first( [](int i) { return i > 2; } );

println("{}", num1.value_or(0));
println("{}", num2.value_or(0));

Output:

1
3

last()

Returns the last element of the range, or the last element that fulfills a given predicate.

Signature:

std::optional<output_t> last() const;

template <typename TPredicate>
std::optional<output_t> last(const TPredicate& predicate) const;

Example:

const vector numbers { 1, 2, 3, 4 };

optional<int> num1 = linq::from(&numbers)
                               .last();

optional<int> num2 = linq::from(&numbers)
                               .last( [](int i) { return i < 3; } );

println("{}", num1.value_or(0));
println("{}", num2.value_or(0));

Output:

4
2
⚠️ **GitHub.com Fallback** ⚠️