C++ Program to Implement Array in STL



An array is a collection of elements of the same type such as integers, string, etc.

Array in STL

In C++ Standard Template Library (STL) , we use std::array container to create arrays with a fixed size. the size cannot be changed once created.

It works like a normal array but with extra features like knowing its own size and working with STL functions.

Syntax

Following is the syntax to create an array in C++ STL:

array(data_type, size) array_name = {va1, val2,...valn};

Here,

  • data_type: It specifies the type of data array will accept. it can be any type such as: int, char, string, etc.
  • size: The number of maximum elements an array can hold.
  • val1, val2,...valn: These are the values of an array of same type.

Note: To use std::array to the program, we need to include its header at the top of your program:

#include<array>

Example 1: Integer Array Implementation

In this example, we create an array of int type having size 3, and initialize values in the curly braces {1, 2, 3}:

#include<iostream>
#include<array>       // for std::array
using namespace std;
int main() {
    
    // Create and initialize a std::array of integers
    array<int, 3> numbers = {1, 2, 3};
    cout<<"An array elements are: ";
    for (int num : numbers) {
        cout<<num<<" ";
    }
    cout<<endl;
}

Following is the output to the above program:

An array elements are: 1 2 3 

Example 2: Character Array Implementation

The example below creates an array of char type having size 5 in STL with values {'a', 'e', 'i', 'o', 'u'}. We iterate over the array to print each value one by one:

#include<iostream>
#include<array>       // for std::array
using namespace std;
int main() {
    
    // Create and initialize a std::array of integers
    array<char, 5> vowels = {'a', 'e', 'i', 'o', 'u'};
    cout<<"An array elements are: ";
    for (char v : vowels) {
        cout<<v<<" ";
    }
    cout<<endl;
}

The above program produces the following output:

An array elements are: a e i o u 

Example 3: Printing EVEN Numbers

In this example, we retrieve all the even numbers from an STL array which having values {10, 11, 12, 13, 14, 15}:

#include<iostream>
#include<array>       // for std::array
using namespace std;
int main() {
    
    // Create and initialize a std::array of integers
    array<int, 5> numbers = {11, 12, 13, 14, 15};
    cout<<"An array elements are: ";
    for(int num : numbers){
        cout<<num<<" ";
    }
    cout<<"\nThe even numbers are: ";
    for (int num : numbers) {
       if(num % 2 == 0){
           cout<<num<<" ";
       }
    }
    cout<<endl;
}

The above program produces the following output:

An array elements are: 11 12 13 14 15 
The even numbers are: 12 14 
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-05-27T17:06:54+05:30

509 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements