×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Array in C++ Standard Template Library (STL) with its common functions

C++ STL std::array class with its common functions: Here, we will learn about the array class with its common functions with Example in C++ Standard Template Library.
Submitted by IncludeHelp, on September 01, 2018

C++ STL Array Class

"array" is a container in C++ STL, which has fixed size, which is defined in "array" header.

Declaration

array <data_type, size> array_name = {initializer_list};
    
Example:
array<int,5> values {10, 20, 30, 40, 50};

Array Class's Common Functions

  1. array::operator[] - Gets and sets a reference to an element based on given index.
  2. array.empty() - Returns true if array is empty
  3. array.size() - Returns the total number of elements in the array
  4. array.front() - Return the first element
  5. array.back() - Returns the last element
  6. array.at(index) - Returns the element from given index
  7. array.begin() - Returns the reference pointing to the first element
  8. array.end() - Returns the reference punting to the last element

Example of C++ STL Array Class

#include <array>
#include <iostream>

using namespace std;

int main() {
  // array declaring and initialization
  array<int, 5> arr = {10, 20, 30, 40, 50};

  // checking array is empty or not by using empty()
  if (arr.empty())
    cout << "Array is empty!!!" << endl;
  else
    cout << "Array is not empty!!!" << endl;

  // Array functions
  cout << "size: " << arr.size() << endl;
  cout << "first element: " << arr.front() << endl;
  cout << "last  element: " << arr.back() << endl;
  cout << "0th element: " << arr.at(0) << endl;
  cout << "3rd element: " << arr.at(3) << endl;

  // printing all array elements are: ";
  for (auto i = arr.begin(); i != arr.end(); i++) cout << *i << " ";
  cout << endl;

  return 0;
}

Output

Array is not empty!!!
size: 5
first element: 10
last  element: 50
0th element: 10
3rd element: 40
10 20 30 40 50 

Reference: C++ std::array

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.