Built-in functions of std::array

             The built-in header file <array> has variety of member functions. The way of using these functions in c++ programs as follows…

‘size()’:

              This function finds of the size of an array.

C++ Program:

 #include <iostream>

#include <array>

using namespace std;

int main() {

    std::array<int, 8> x = {1, 2, 3, 4, 5,6,7,8};

    size_t size = x.size();

    cout<<"the size of array is:"<<size<<endl;

    return 0;

}

Output:

the size of array is:8

‘at()’:

              This function finds an element in a position.

Sample c++ code:

#include <iostream>

#include <array>

using namespace std;

int main() {

    int pos,i;

    std::array<int, 8> x = {1, 2, 3, 4, 5,6,7,8};

    cout<<"Enter the position:"<<endl;

    cin>>pos;

    int a_value = x.at(pos);

    cout<<"The array elements are:"<<endl;

    for(i=0;i<8;i++)

    {

        cout<<x[i]<<endl;

    }

    cout<<"The element at the postion in array is:"<< a_value<<endl;

    return 0;

}

Output:

Enter the position:

6

The array elements are:

1

2

3

4

5

6

7

8

The element at the postion in array is:7

‘fill()’:

              The function fills a particular value to array.

C++ Program:

#include <iostream>

#include <array>

using namespace std;

int main() {

    int a,i;

    std::array<int, 8> x = {1, 2, 3, 4, 5,6,7,8};

    cout<<"Enter the value to fill:"<<endl;

    cin>>a;

    x.fill(a);

    cout<<"The array elements are:"<<endl;

    for(i=0;i<8;i++)

    {

        cout<<x[i]<<endl;

    }

    return 0;

}

Output:

Enter the value to fill:

6

The array elements are:

6

6

6

6

6

6

6

6

‘swap()’:

              This program exchanges the value of an array into another array.

C++ Code:

#include <iostream>

#include <array>

using namespace std;

int main() {

    int a,i;

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

    std::array<int, 5> x2 = {6, 7, 8, 9, 10};

    cout<<"The elements of array1:"<<endl;

    for(i=0;i<5;i++)

    {

        cout<<x[i]<<endl;

    }

    cout<<"The elements of array2:"<<endl;

    for(i=0;i<5;i++)

    {

        cout<<x2[i]<<endl;

    }

    x.swap(x2);

    cout<<"The array elements of array2 after swapping:"<<endl;

    for(i=0;i<5;i++)

    {

        cout<<x2[i]<<endl;

    }

    return 0;

}

Output:

The elements of array1:

1

2

3

4

5

The elements of array2:

6

7

8

9

10

The array elements of array2 after swapping:

1

2

3

4

5

Hope, the member functions of std:: array is useful to you. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.