C++ | C++ STL array container

Keywords: C++

C++ | C++ STL array container

Detailed usage of C++ array(STL array) container

array Container is C++ New Sequence Container in 11 Standard ( std::array In a nutshell, it adds some member functions and global functions on the basis of C++ normal arrays. It is safer and less efficient to use than normal arrays.

Unlike other containers, array containers are fixed in size and cannot dynamically expand or shrink, which means that the process of using the container cannot change its size by adding or removing elements; it only allows access to or replacing stored elements. Standard Manual

#include <array>
using namespace std; // Use std namespace by default
template < class T, size_t N > class array;

T: The type of element contained. The alias is the member type array::value_type.

N: The size of the array, expressed as the number of elements (must be constant).

std::array<double, 10> values; // Create array container with 10 double type elements initialized to 0
std::array<double, 10> values = {0.5, 1.0, 1.5, 2.0, 2.5};

Summary of array container member functions

Member functionfunction
begin()Returns a random access iterator pointing to the first element in the container.
end()Returns a random access iterator pointing to a location after the last element of a container, usually in conjunction with begin().
rbegin()Returns a random access iterator pointing to the last element.
rend()Returns a random access iterator pointing to a location before the first element.
cbegin()It does the same thing as begin(), except that it adds a const attribute to it and cannot be used to modify elements.
cend()It does the same thing as end(), except that it adds a const attribute to it and cannot be used to modify elements.
crbegin()It does the same thing as rbegin(), except that it adds a const attribute to it and cannot be used to modify elements.
crend()It does the same thing as rend(), except that it adds a const attribute to it and cannot be used to modify elements.
size()Returns the number of current elements in the container whose value is always equal to the second template parameter N that initializes the array class.
max_size()Returns the maximum number of elements a container can hold, always equal to the second template parameter N that initializes the array class.
empty()Determining whether a container is empty is the same as conditioning by size()==0, but it may be faster.
at(n)Returns a reference to an element at position n in a container, which automatically checks if n is within a valid range, or throws an out_of_range exception if not.
front()Returns a direct reference to the first element in the container, which is not applicable to an empty array container.
back()Returns the direct application of the last element in the container, which is also not applicable to an empty array container.
data()Returns a pointer to the first element of the container Pointer With this pointer, similar functions such as copying all elements in a container can be achieved.
fill(val)Assign the value valto each element in the container.
array1.swap(array2)Exchange all elements in array1 and array2 containers, provided they have the same length and type.

Instance 1

/*******************************************************************
 *   > File Name: array-begin.cpp
 *   > Create Time: 2021 September 28, 2002 22:33:02
 ******************************************************************/
#include <iostream>
#include <array>
using namespace std;

int main(int argc, char* argv[])
{
    std::array<int, 5> myarray = {2, 16, 77, 34, 50};
    
    std::cout << "myarray contains:";
    /*auto Enables the compiler to automatically determine the type of variable, all values in the output container*/
    for(auto it = myarray.begin(); it != myarray.end(); ++it){
        std::cout << ' ' << *it;
    }

    //Output specified location elements using get() overloaded function
    std::cout << endl << get<3>(myarray) << endl;;

    return 0;
}

Compile, run:

PS D:\study\cplusplus\day11> make
g++ -o array-begin array-begin.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day11> .\array-begin.exe
myarray contains: 2 16 77 34 50

C++ STL array random access iterator

array supports member functions of iterators

begin()Returns a forward iterator pointing to the first element in the container; if the container is of type const, the function returns a constant forward iterator.
end()Returns a forward iterator pointing to a position after the last element of a container; if it is a const-type container, the function returns a constant forward iterator. This function is usually used in conjunction with begin().
rbegin()Returns a reverse iterator pointing to the last element; if it is a container of type const, the function returns a constant reverse iterator.
rend()Returns a reverse iterator pointing to a position before the first element. If it is a container of type const, the function returns a constant reverse iterator. This function is usually used in conjunction with rbegin().
cbegin()Similar to begin(), except that it returns an iterator type of constant forward iterator that cannot be used to modify elements.
cend()Same functionality as end(), except that it returns an iterator type of constant forward iterator that cannot be used to modify elements.
crbegin()It does the same thing as rbegin(), except it returns an iterator type of constant reverse iterator that cannot be used to modify elements.
crend()It does the same thing as rend(), except that it returns an iterator type of constant reverse iterator that cannot be used to modify elements.

begin()/end() and cbegin()/cend()

Instance 2

/*******************************************************************
 *   > File Name: array-iterator.cpp
 *   > Create Time: 2021 28 September 2003 23:08:10
 ******************************************************************/
#include <iostream>
#include <array>
using namespace std;

int main(int argc, char* argv[])
{
    array<int, 5> values;
    int h = 1;
    #if 0
    auto first = values.begin(); // OK
    auto last = values.end(); // OK
    #else
    auto first = std::begin(values); // OK
    auto last = std::end (values); // OK
    #endif

    /* Initialization Container */
    while(first != last){
        *first = h;
        ++first; // ++ means that the iterator moves one bit to the right
        h++;
    }

    first = values.begin();
    while(first != last){
        cout << *first << " ";
        ++first; // ++ means that the iterator moves one bit to the right
    }
    cout << endl;

    auto first1 = values.cbegin();
    while(first1 != values.cend()){
        /* Elements can be accessed using const type iterators */
        cout << *first1 << " "; //Cannot be used to modify elements
        ++first1; // ++ means that the iterator moves one bit to the right
    }
    cout << endl;

    return 0;
}

Compile, run:

PS D:\study\cplusplus\day11> make
g++ -o array-iterator array-iterator.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day11> .\array-iterator.exe
1 2 3 4 5
1 2 3 4 5

rbegin()/rend() and crbegin()/crend()

Example 3

/*******************************************************************
 *   > File Name: array-iterator1.cpp
 *   > Create Time: 2021 September 28, 2003 23:25:10
 ******************************************************************/
#include <iostream>
#include <array>
using namespace std;

int main(int argc, char* argv[])
{
	/* Define an array container values */
    array<int, 5> values = {1, 25, 33, 16, 10};
    auto first = values.rbegin();
    auto last = values.rend(); 

    while(first != last){
        cout << *first << ' ';
        ++first; // ++ means that the iterator moves one bit to the left
    }
    cout << endl;

    return 0;
}

Compile, run:

PS D:\study\cplusplus\day11> make
g++ -o array-iterator1 array-iterator1.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day11> .\array-iterator1.exe
10 16 33 25 1

Several ways for C++ STL array containers to access elements

Accessing a single element in an array container

The elements in the container are accessed and used directly by the container name [].

values[4] = values[3] + 2.O*values[1];

Use the at() member function provided by the array container.

values.at (4) = values.at(3) + 2.O*values.at(1);

Use the get<n>template function to get container elements.

array<string, 5> words{ "one","two","three","four","five" };
cout << get<3>(words) << endl; // Output words[3]

From the data() member function, you get the value that points to the first element of the container Pointer.

array<int, 5> words{1,2,3,4,5};
cout << *( words.data()+1); // Output words[1]

Accessing multiple elements in the array container

The size() function provided by the array container returns the number of elements in the container (the function returns a value of type size_t).

double total = 0;
/* Extract the elements in the container one by one and calculate their sum  */
for(size_t i = 0 ; i < values.size() ; ++i)
{
    total += values[i];
}

By calling the empty() member function of the array container, you know if there are elements in the container.

if(values.empty()){
    std::cout << "The container has no elements.\n";
}  else{
    std::cout << "The container has "<< values.size()<<"elements.\n";  
}

Posted by jandante@telenet.be on Tue, 28 Sep 2021 12:47:28 -0700