std::ranges
algorithms work seamlessly with container views like std::span
and std::string_view
, providing a flexible way to operate on sub-ranges or specific sections of data without copying it.
std::span
std::span
is a non-owning view over a contiguous sequence of elements. Here’s an example using std::ranges::count()
with std::span
:
#include <algorithm>
#include <iostream>
#include <span>
#include <vector>
int main() {
std::vector<int> numbers {1, 2, 3, 4, 4, 5};
std::span<int> numbersView(
numbers.data(), numbers.size());
auto foursCount = std::ranges::count(
numbersView, 4);
std::cout << "Count of fours: " << foursCount;
}
Count of fours: 2
std::string_view
std::string_view
provides a view over a string without owning the actual string data. Here's an example using std::ranges::count()
with std::string_view
:
#include <algorithm>
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string text = "hello world";
std::string_view textView(text);
auto lCount = std::ranges::count(textView, 'l');
std::cout << "Count of 'l': " << lCount;
}
Count of 'l': 3
std::string_view
is great for read-only string operations.By using container views with std::ranges
algorithms, you can write efficient, flexible, and clear code. This approach is particularly useful in modern C++ for handling large datasets and optimizing performance.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the 5 main counting algorithms in the C++ standard library: count()
, count_if()
, any_of()
, none_of()
, and all_of()