Interfaces to the Standard Library
The
std::array template provides the same interface as a standard container class. Therefore, you can use the uniform type names
iterator,
const_iterator,
reference,
size_type,
difference_type,
value_type, and so on:
typedef std::array <int,5> myints;
myints::size_type sz = a.size();
myints::iterator it = a.begin();
while (it++ != a.end())
cout<<*it<<endl;
To assign a single value to every element in the array, use the
fill() member function:
array<int,5> arr; //no initialize list,
arr.fill(12); //assign the value 12 to every element
All standard algorithms operate on
std::array directly, as with vectors. Consider a function template
sum(). It takes a type
T that meets the container
concept requirements and sums up its elements:
template<Container C> C::value_type sum(const C& c)
{
return accumulate(c.begin(),c.end(),0);
}
array<int,5> ai5={0,2,4,8,10};
vector<int> vi={0,1,3};
// ...
int sum1 = sum(ai5);
int sum2 = sum(vi);
Unlike with built-in arrays, a zero-length
std::array is valid, albeit with certain restrictions:
array<int,0> a0; //OK, no elements
The C++ standard guarantees that when
N == 0,
begin() == end() == unique value. However, the return value of
data() is unspecified, as are the effects of calling
front() and
back() for a zero-sized array:
int* p = a0.data(); //unspecified; don't do that
As with other standard containers, the member function
empty() reports whether the array is empty:
bool has_data =a0.empty();
Compiler Support
The new
std::array class template is now supported by several leading compilers, so you should consider using it as an efficient alternative to vectors when dealing with fixed-sized sequences.
To enable C++09 features, you may need to turn on special compilation options, for example, -std=c++0x on GCC. Check your compiler's online documentation for specific details.