Skip to main content

C++ STL Array Container – std::array

Here you will learn about STL Array Container in C++ i.e. std::array.

I Hope you know about C-type arrays (arrays in C language). Since C++ is just extension to C language we can use those. The main property is that, Array contains series of elements of same type placed in contiguous memory locations. i.e suppose we have marks of 100 students, instead of declaring 100 variables, using array the 100 int values can store in contiguous memory locations and all can be accessed through same identifier, by just adding some number to identifier which points to particular index.

Declaring Normal Array

Syntax: type arrayName[size];

Example: int marks[5];  //This is array of type int which stores marks of 5 students

Initializing Arrays

int marks [5] = { 10, 23, 15, 20, 25 };

This stores the elements in contiguous locations, that in index 0, element 10 will be stored remaining follows as same.

Accessing the elements of the array:

Syntax: arrayName[index];

Example: marks[2]; //This will gives the value of the element at 2nd index of the array marks, which is 15.

If we try to access giving a number which is greater than size of the array in place of index, it will raise an error called arrayIndexOutof bound error.

These are directly implemented as a language feature, inherited form C language. They probably suffer from an excess of optimization. Very less inbuilt functions.

C++ STL Array

To overcome issues with language built-in arrays, C++ Standard library (STL) provides arrays as a type of container which includes rich set of operations. It is a type template (a class template) defined in header <array>.

To work with that array we must include array header class in our code.

#include<array> // Including array container header file

These offer a better alternative for C-type arrays. The advantages over C-type arrays are:

  • C-style arrays don’t know its own size. But Array Containers know their own size. So when passing array to a function here we no need to pass it’s size unlike where we do in C-type arrays.
  • C-style arrays worked and entirely accessed by pointers, where Array Containers are not.
  • Array Containers have more inbuilt functions than C-style arrays. So these are more efficient.

Syntax of STL Array

array< datatype, size > arrayName;

Operations on Array Container

Lets discuss about some important functions of stl array with program examples.

at(): This method used to access the elements of the array.

Syntax: arrayName.at(index);

In the place of index, if we give number more than the size of the array it will give array out_out_range exception.

get(): This is also used to access the elements of the array. But this method doesn’t belongs to the class array. It is over loaded from class tuple.

Syntax: get<index> (arrayName);

[] operator: This is also used to access the elements of the array. This style accessing is same as C-style arrays.

Example program to show about these three operations on array:

#include <iostream>
#include <array>
#include <tuple> // This is for get() method

using namespace std;

int main(){
        // Initializing arrays
        array<int,5> marks = { 87, 98, 70, 90, 100};
        
        // accessing and printing array elements using at()
        cout << "elements using at()" << endl;
        for(int i=0;i<5;i++) cout << marks.at(i) << endl;
        
        // accessing and printing array elements using []  operator
        cout << "elements using [] operator" << endl;
        for(int i=0;i<5;i++) cout << marks[i] << endl;
        
        // accessing and printing array elements using get()
        cout << "elements using get()" << endl;
        cout << get<0> (marks)<<endl;
        cout << get<1> (marks)<<endl;
        cout << get<2> (marks)<<endl;
        cout << get<3> (marks)<<endl;
        cout << get<4> (marks)<<endl;
        return 0;
}

Output

elements using at()
87
98
70
90
100
elements using [] operator
87
98
70
90
100
elements using get()
87
98
70
90
100

front(): This returns the first element of the array.

back(): This returns the last element of the array.

Example program to show front() and back() operations:

#include <iostream>
#include <array>

using namespace std;

int main(){
        array<int,5> marks = {87, 98, 70, 90, 100};
        
        // first element
        cout << "first element of the array is ";
        cout << marks.front() << endl;
        
        // last element
        cout << "last element of the array is ";
        cout << marks.back() << endl;
        return 0;
}

Output

first element of the array is 87
last element of the array is 100

size(): It returns the number of elements in the array. C-style arrays fails in this.

max_size(): It returns the maximum number of elements array can hold i.e. the size with which array is declared. The size() and max_size() return the same value.

empty(): If array size is zero this function returns true (1). Else returns false value

fill(): This function used to fill the entire array with particular value.

Example program to demonstrate above four functions:

#include <iostream>
#include <array>

using namespace std;

int main(){
        array<int,5> marks = { 87, 98, 70, 90 };
        array<int,0> dup_array;
        
        // number of the elements in the array
        cout << "the number of elements in the array is ";
        cout << marks.size() << endl;
        
        // maximum number of elements array can hold
        cout << "maximum number of elements in the array is ";
        cout << marks.max_size() << endl;
        
        //checking size of array is empty or not
        int flag = dup_array.empty();
        if(flag==1) cout << "Array is empty" << endl;
        else cout << "Array is not empty" << endl;
                
        // filling array with some particular element
        marks.fill(35);
        
        //checking array after filling
        for(int i=0;i<5;i++) cout << marks[i] << " ";
        cout << endl;
        return 0;
}

Output

the number of elements in the array is 5
maximum number of elements in the array is 5
Array is empty
35 35 35 35 35

swap(): This will swap the all the elements of one array1 to array2 and from array2 elements to array1. But condition is that both arrays must be of same type and must be same size.  Swapping will done in such a way that, each ith indices of of both arrays will be swapped.

Example program:

#include <iostream>
#include <array>

using namespace std;

int main(){
        array<int,5> array1 = { 1, 2, 3, 4, 5 };
        array<int,5> array2 = {11, 22, 33, 44, 55 };
        
        cout<< "array1 elements before swap" << endl;
        for(int i=0;i<5;i++) cout << array1[i] << " ";
        cout << endl;
        
        cout<< "array2 elements before swap" << endl;
        for(int i=0;i<5;i++) cout << array2[i] << " ";
        cout << endl;
        
        //doing swapping operation
        array1.swap(array2);
        
        cout<< "array1 elements after swap" << endl;
        for(int i=0;i<5;i++) cout << array1[i] << " ";
        cout << endl;
        
        cout<< "array2 elements after swap" << endl;
        for(int i=0;i<5;i++) cout << array2[i] << " ";
        cout << endl;
        return 0;
}

Output

array1 elements before swap
1 2 3 4 5
array2 elements before swap
11 22 33 44 55
array1 elements after swap
11 22 33 44 55
array2 elements after swap
1 2 3 4 5

Comment below if you have any queries or found any information incorrect in above tutorial for C++ STL Array.

The post C++ STL Array Container – std::array appeared first on The Crazy Programmer.



from The Crazy Programmer http://www.thecrazyprogrammer.com/2017/07/stl-array.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...

15 Web Design Trends to Watch in 2018

The modern world is full of extraordinary things that influence our imagination and mood. Our soul needs a perfect atmosphere and impressive spots. To apply such things in practice, we have submitted the list of the web trends that deserve your attention. Robert frost design analysis will meet all your wishes and expectations. Image Source Web Design Trends to Watch in 2018 1. More Organic Shapes Until this year, web design, as well as mobile design, were based on the right-angled and sharp-edged shapes. However, it seems that this year will bring some significant changes in the field of web design. The recent trends will offer the absolute rounded corners. In addition, the web design of 2018 will make the real things look like the cartoonish ones. 2.   Bold Minimalism Although some of you may think that this web design trend will not attract the Internet users. Indeed, the notion of minimalism is often associated with boredom and dullness. However, in this case, bold ...

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and...