How to use typedef with arrays In C++
typedef can be used with arrays for making newer arrays (just like using them with STL data structures). We can easily make new arrays or make arrays of arrays using typedef with arrays, while keeping our code readable, seamlessly.
Syntax:
typedef <data_type> <alias_name> [<size>]
After this <alias_name> can now be used for creating arrays of type- <data_type> and size <size>.
C++
// C++ program to show use of typedef with arrays #include <iostream> using namespace std; int main() { typedef int arr[3]; // Making new 1D array arr array1{ 1 , 1, 1}; cout << "Array output: " << "\n" ; for ( int i = 0; i < 3; i++) { cout << array1[i] << " " ; } cout << "\n" ; // Making new 2D array // Matrix is an array of arrays with size // ( 3 X 3 ) arr matrix[3]; cout << "Matrix output: " << "\n" ; for ( int i = 0; i < 3; i++) { for ( int j = 0; j < 3; j++) { // Initializing the matrix matrix[i][j] = i * j; } } // Outputting the matrix for ( int i = 0; i < 3; i++) { for ( int j = 0; j < 3; j++) { cout << matrix[i][j] << " " ; } cout << "\n" ; } return 0; } |
Array output: 1 1 1 Matrix output: 0 0 0 0 1 2 0 2 4
typedef in C++
typedef keyword in C++ is used for aliasing existing data types, user-defined data types, and pointers to a more meaningful name. Typedefs allow you to give descriptive names to standard data types, which can also help you self-document your code. Mostly typedefs are used for aliasing, only if the predefined name is too long or complex to write again and again. The unnecessary use of typedef is generally not a good practice.
Syntax:
typedef <current_name> <new_name>
Example:
typedef std::vector<int> vInt;
Below is the C++ Program to implement typedef
C++
// C++ Program to implement typedef #include <bits/stdc++.h> using namespace std; int main() { // Now we can make more vectors by using vInt typedef std::vector< int > vInt; // vec1 is a vectorof type int vInt v; v.push_back(190); v.push_back(180); v.push_back(10); v.push_back(10); v.push_back(27); for ( auto X : v) { cout << X << " " ; } return 0; } |
190 180 10 10 27