I was under the assumption that STL functions could be used only with STL data containers (like vector) until I saw this piece of code:
#include <functional>
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int a[] = {9, 8, 7};
cerr << "Sum: " << accumulate(&a[0], &a[3], 0, plus<int>()) << endl;
return 0;
}
It compiles and runs without any warnings or errors with g++, giving the correct output sum of 24.
Is such usage of arrays with STL functions allowed by the C++/STL standard? If yes, how do archaic structures like arrays fit into the grand STL plan of templated iterators, containers and functions? Also, are there any caveats or details in such usage that the programmer should be careful about?
Well, you ask about an array. You can just easily get a pointer to its elements, so it basically boils down to the question whether pointers can be used transparently with STL functions. A pointer actually is the most powerful kind of an iterator. There are different kinds
Now each iterator in the second group supports all the things of all iterators mentioned before it. A pointer models the last kind of iterators – a random access iterator. You may add/subtract an arbitrary integer and you may read and write. And all except the output iterator has a
operator->that can be used to access a member of the element type we iterate over.Normally, iterators have several typedefs as members
std::distance).std::input_iterator_tag, …,std::random_access_iterator_tag. Algorithms can use it to overload on different kinds of iterators (likestd::distanceis faster for random access iterators, because it can just returna - b)Now, a pointer of course does not have those members. C++ has an
iterator_traitstemplate and specializes it for pointers. So if you want to get the value type of any iterator, you doAnd whether it is a pointer or some other iterator, it will give you the value_type of that iterator.
So – yes, a pointer can very well be used with STL algorithms. As someone else mentioned, even
std::vector<T>::iteratorcan be aT*. A pointer is a very good example of an iterator even. Because it is so exceedingly simple but at the same time so powerful that it can iterate over a range.