Ch9.15: Using Container Ranges with Algorithms
Overview
All fast_io containers provide begin() and
end() iterators, which means they work with the C++ standard
library algorithms via <algorithm> and
<ranges>.
1. Using std::ranges with fast_io Containers
#include <fast_io_dsal/vector.h>
#include <algorithm>
#include <ranges>
#include <fast_io.h>
int main() {
::fast_io::vector<::std::size_t> v{5zu, 3zu, 1zu, 4zu, 2zu};
// Sort using std::ranges
::std::ranges::sort(v);
// v is now {1zu, 2zu, 3zu, 4zu, 5zu}
// Find an element
auto it = ::std::ranges::find(v, 3zu);
if (it != v.end()) {
::fast_io::io::println("Found 3 at index ",
static_cast<::std::size_t>(it - v.begin()));
}
// Count elements greater than 2
auto count = ::std::ranges::count_if(v, [](::std::size_t x) { return x > 2zu; });
::fast_io::io::println("Count > 2: ", count); // 3
// Erase-remove idiom
::fast_io::vector<::std::size_t> w{1zu, 2zu, 3zu, 2zu, 4zu, 2zu, 5zu};
auto new_end = ::std::ranges::remove(w, 2zu);
w.erase(new_end, w.end());
// w is now {1zu, 3zu, 4zu, 5zu}
}
2. Free Functions: erase() and erase_if()
You can also use the free functions erase() and
erase_if() that are provided for all containers:
::fast_io::vector<::std::size_t> v{1zu, 2zu, 3zu, 2zu, 4zu, 2zu, 5zu};
// Remove all 2s
auto removed = erase(v, 2zu);
// v is now {1zu, 3zu, 4zu, 5zu}, removed == 3
// Remove elements matching a predicate
auto removed2 = erase_if(v, [](::std::size_t x) { return x > 3zu; });
// v is now {1zu, 3zu}, removed2 == 2
Key takeaways
- All
fast_iocontainers work withstd::ranges::algorithms. - The free functions
erase()anderase_if()are provided for all containers. std::ranges::sort,std::ranges::find,std::ranges::count_ifall work directly.- The erase-remove idiom works with
std::ranges::removefollowed byerase().