Component of the Week #2: bsl_iterator
- Summary:
Provides free functions like
size,begin, andendthat work on C-style arrays and array-like types (likevector)
Have you ever wanted to get the size of a C-style array and grown tired of
typing sizeof myArray / sizeof *myArray? Or written a function template that
needs to work seamlessly with C-style arrays, bsl::vector, bsl::array, etc?
There is a BDE component for that! And that component is bsl_iterator.
bsl_iterator contains a bunch of free functions that make such scenarios easier to handle.
bsl::size will get you the container’s size:
int myArray[] = {1, 2, 3};
bsl::cout << bsl::size(myArray);
And it will work just as well for any container that has .size():
bsl::vector<int> vec{1, 2, 3};
bsl::set<int> set{4, 5, 6, 6};
bsl::cout << bsl::size(vec) << " " << bsl::size(set);
If you want the size converted to appropriate signed type, there’s
bsl::ssize:
bsl::vector<int> vec{1, 2, 3};
for (auto i = bsl::ssize(vec) - 1; i >= 0; --i) {
bsl::cout << vec[i] << '\n';
}
Need to get iterators for C-style arrays and containers in a uniform manner?
You have bsl::begin, bsl::end, and their const and reverse
variants (e.g., bsl::crbegin that gives you a const reverse begin
iterator):
bsl::array arr{1, 2, 3};
for (auto it = bsl::crbegin(arr); it != bsl::crend(arr); ++it) {
bsl::cout << *it << '\n';
}
And so much more! Check out the documentation for bsl_iterator.