This all are the static ways cause we have memory is created at compile time
#include <iostream>
#include <array>
using namespace std;
void normPrint(int *arr,int (&aref)[5], int &m){
// *arr is a pointer array which
// aref is another name of the original array a
// Note aref is not another array it is a another name
cout<<"pass by pointer"<<endl;
for(int i = 0;i<m;i++){
cout<<arr[i]<<" ";
}
cout<<endl<<"pass by refernce variable"<<endl;
for(int i = 0;i<5;i++){
cout<<aref[i]<<" ";
}
}
void stlPrint(array<int, 5> &arr, int m){
cout<<"\n";
for (int &element : arr) {
cout<<element<<" ";
}
}
int main() {
int arr[100] ={5,7,8,9,10};
int a[] ={1,2,3,4,5};
// this will give size as 100
// not a good way
// int n = sizeof(arr)/sizeof(arr[0]);
int n = 5;
normPrint(arr,a,n);
// STL
array<int, 5> myArray = {1, 2, 3, 4, 5};
int m = myArray.size();
// Method 1
// Using iterators to print the elements of the array
for (auto it = myArray.begin(); it != myArray.end(); ++it) {
cout << *it << " ";
}
// Method2
// This automatically iterates over the elements in the array, and there's no need to use explicit iterators.
cout<<"\n";
for(auto i:myArray){
cout<<i<<" ";
}
// Method3
// Using pass by refernce
stlPrint(myArray,m);
return 0;
}
Comments
Post a Comment