logo codesdope

std::array


Before learning about std::array, let's first see the need for it.

std::array is a container that wraps around fixed size arrays. It also doesn't loose the information of its length when decayed to a pointer.

You know that when we pass an array (also known as C-style array) to a function, the address of the array gets passed to the function i.e. the pointer to the array gets passed to the function. Thus, the information about the size of the array gets lost.

To deal with such situations, we use std::array and std::vector. In this chapter, we will be looking at std::array and std::vector in the next one.

Let's first have a look at the syntax of std::array.

Declaration of std::array


The declaration of std::array is as follows:

std::array<datatype,array_size> array_name;

This is a simple declaration of an std::array. Let's look at the declaration of an integer array of length 5.

std::array<int, 5> n;

Here 'n' is an std::array of type int and length 5.

In order to use std::array, we need to include the following code in the beginning of our program.

#include <array>

Initialization of std::array


Like arrays, we initialize an std::array by simply assigning it values at the time of declaration. For example, we will initialize an integer type std::array named 'n' of length 5 as shown below;

std::array<int, 5> n = {1, 2, 3, 4, 5};

There is another way of initializing an std::array which is shown below.

std::array<int, 5> n { {1, 2, 3, 4, 5} };

The length of an std::array must be known at the time of compilation.

Unlike C-style arrays in which writing array length at the time of initialization was not necessary, we cannot omit writing the array length in case of std::array. For example, the following initialization is incorrect.

std::array n { {1, 2, 3, 4, 5} };   // incorrect

We can also assign values to the array as follows.

std::array n;
n = {1, 2, 3, 4, 5};

std::array functions exactly the same as C-style arrays. Now, after knowing how to declare and assign values to an array, let's see a simple example of printing the value of an element of an std::array.

#include <iostream>
#include <array>

int main()
{
    std::array<int, 5> n = { 1, 2, 3, 4, 5 };
 
    std::cout << n[2] << std::endl;
 
    return 0;
}
Output
3

In this example, we simply printed the value of the third element of the array by printing n[2].

If you are getting any compilation error, instruct your compiler to use C++11 by using the following command to compile:
g++ -std=c++11 -o filename filename.cpp

Length of std::array


We can return the length of an std::array using the size() function. The following example illustrates its use.

#include <iostream>
#include <array>

int main()
{
    std::array<int, 5> n = { 1, 2, 3, 4, 5 };
 
    std::cout << "Number of elements in the array are : " << n.size() << std::endl;
 
    return 0;
}
Output
Number of elements in the array are : 5

Thus, the size() function returned the number of elements in the array. Now, let's look at another example just to make you realize that an std::array functions no different than a C-type array.

#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<int, 5> n;
    
    //taking values of elements from user
    for(int i = 0; i < n.size() ; i++)
    {
	cout << "Enter value of n[" << i << "]"<< endl;
    	cin >> n[i];
    }
 	
    /* printing the values of elements of array */
    for (int j = 0; j < n.size(); j++ ) 
    {
        cout << "n[" << j << "] = " << n[j] << endl;
    }
    return 0;
}
Output
Enter value of n[0]
1
Enter value of n[1]
2
Enter value of n[2]
3
Enter value of n[3]
4
Enter value of n[4]
5
n[0] = 1
n[1] = 2
n[2] = 3
n[3] = 4
n[4] = 5

In this example, we simply took the values of the elements of the array using the first for loop and printed them using the second for loop. Notice that we did not write std:: before array in the declaration of the array because we wrote the statement using namespace std before the main function.

Passing std::array to function


Let's look at an example of passing an std::array to a function.

#include <iostream>
#include <array>

using namespace std;

void printArray(const std::array<int, 5> &n)
{
    std::cout << "length: " << n.size() << endl;

    for (int j = 0; j < n.size(); j++ ) 
    {
        cout << "n[" << j << "] = " << n[j] << endl;
    }

}

int main()
{

    array<int, 5> n = {1,2,3,4,5};

    printArray(n);

    return 0;
}
Output
length: 5
n[0] = 1
n[1] = 2
n[2] = 3
n[3] = 4
n[4] = 5

void printArray(const std::array<int, 5> &n) - const is used here to prevent the compiler from making a copy of the array and this enhances the performance.
The passed array will be n in this function as &n is the parameter of the function 'printArray'.

Also, use of the size function on the array inside the function gave us 5 thus, showing that an std::array doesn't lose its property of length when passed to a function.

Member Functions


There are a number of member functions of std::array (pre-defined functions). Let's see some of these methods.

at()


at() function is used to access the element at specified position (index). Let's rewrite the above example by using the at() function with the array name to take input and print the values of the elements of an std::array.

#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<int, 5> n;
    
    //taking values of elements from user
    for(int i = 0; i < n.size() ; i++)
    {
		cout << "Enter value of n[" << i << "]"<< endl;
    	cin >> n.at(i);
  	}
 	
 	/* printing the values of elements of array */
  	for (int j = 0; j < n.size(); j++ ) 
  	{
    	       cout << "n[" << j << "] = " << n.at(j) << endl;
  	}
    return 0;
}
Output
Enter value of n[0]
1
Enter value of n[1]
2
Enter value of n[2]
3
Enter value of n[3]
4
Enter value of n[4]
5
n[0] = 1
n[1] = 2
n[2] = 3
n[3] = 4
n[4] = 5

Here n.at(i) is the same as writing n[i], which means the element at the ith position.

front()


front() function returns the first element of an std::array.

#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<double, 4> arr = {5.6, 4.5, 4.7, 4.5};
    cout << arr.front();
    
    return 0;
}
Output
5.6

back()


It returns the last element of an std::array.
#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<char, 6> ch = {'a', 'b', 'c', 'd', 'e', 'f'};
    cout << ch.back();
    
    return 0;
}
Output
f

empty()


This function checks whether an std::array contains any element or not. It returns 1 if the length of an std::array is 0 and 0 if not.

#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<int, 2> a1 = {1, 2};
    array<int, 0> a2;
    cout << a1.empty() << endl;
    cout << a2.empty() << endl;
    
    return 0;
}
Output
0
1

Since a1 contains 2 elements, so a1.empty() returned 1 and since a2 does not contain any element, a2.empty() returned 0.

max_size()


This function returns the maximum number of elements that the std::array can hold. The following example will make it clear.

#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<int, 8> arr;
    cout << arr.max_size() << endl;
    
    return 0;
}
Output
8

fill()


fill() function fills all the elements of the std::array with the same specified value.

#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<int, 4> arr = {1, 2, 3, 4};
    arr.fill(2);
    cout << arr[3] << endl;
    
    return 0;
}
Output
2

In this example, arr.fill(2) assigned 2 to all the elements of arr. Therefore we got 2 when we printed the value of arr[3].

swap


This function swaps the contents i.e. it exchanges the value of one std::array with that of another.

#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<int, 4> a1 = {1, 2, 3, 4};
    array<int, 4> a2 = {5, 6, 7, 8};
    a1.swap(a2);
    
    //printing the values of the elements of a1
    cout << "Elements of a1" << endl;
    for (int j = 0; j < a1.size(); j++ ) 
  	{
    	cout << a1[j] << endl;
  	}
  	
  	//printing the values of the elements of a2
  	cout << "Elements of a2" << endl;
    for (int j = 0; j < a2.size(); j++ ) 
  	{
    	cout << a2[j] << endl;
  	}
    
    return 0;
}
Output
Elements of a1
5
6
7
8
Elements of a2
1
2
3
4

Here, a1.swap(a2) interchanged the values of the two std::array.

Iterators


Instead of indices, we can also use iterators to iterate over a container (e.g. std::array). An iterator is a kind of pointing item which can be pointed to an element of a container and has the ability to iterate over the container. It means that if we have an iterator at the beginning of an std::array then, it can go over the entire std::array pointing each item of the std::array.

We are provided with the following iterator functions:

  • begin
  • end
  • rbegin
  • rend

begin - Returns an iterator to the first element of the container.

begin in C++

end - Returns an iterator to the end i.e. the element after the theoretical last element of the container.

end in C++

rbegin - Returns a reverse iterator to the first element of the reversed container.

rbegin in C++

rend - Returns a reverse iterator to the theoretical element preceding the first element of the container.

rend in C++

Let's see an example to understand this.

#include <iostream>
#include <array>
#include <iterator>

using namespace std;

int main()
{
    array<int, 4> a = {1, 2, 3, 4};

    for(auto i = a.begin(); i != a.end(); ++i)
    {
    	cout << *i << endl;
    }
    
    return 0;
}
Output
1
2
3
4

auto i = a.begin() - You must be thinking the reason for using auto here. It is used to automatically assign the correct type to the variable i by the compiler. You will learn more about it in the chapter 'Storage classes'.

cout << *i << endl; - *i is used to access the element at i or the element at which i is pointing.

Rest of the code is simple to understand.

sort


sort is used to sort the elements in a range in ascending order. We need to add a header algorithm to use it. Let's see it working through an example.

#include <iostream>
#include <array>
#include <iterator>
#include <algorithm>//for sort

using namespace std;

int main()
{
    array<int, 4> a = {47, 23, 90, 1};

    sort(a.begin(),a.end());

    for(auto i = a.begin(); i != a.end(); ++i)
    {
    	cout << *i << endl;
    }
    
    return 0;
}
Output
1
23
47
90

You can see that the function sort arranged the array a in ascending order.

Everybody should know how to program a computer because it teaches you how to think.
-Steve Jobs

Share what you know
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.