thespeedracer38

Linear Search in C++ using dynamic memory allocation

Feb 4th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. /*  Write a program to create an array dynamically
  2.     using new and freeing it using delete
  3. */
  4.  
  5. #include <iostream>
  6. #include <cstdlib>
  7.  
  8. using namespace std;
  9.  
  10. class Vector{
  11.     int *arr, size;
  12.     public:
  13.         Vector(int);
  14.         int search(int);
  15.         ~Vector();
  16.         friend istream& operator >>(istream&, Vector&);
  17.         friend ostream& operator <<(ostream&, Vector&);
  18. };
  19.  
  20. inline Vector::Vector(int size){
  21.     Vector::size = size;
  22.     arr = new int[Vector::size];
  23. }
  24.  
  25. int Vector::search(int key){
  26.     for(int i = 0; i < size; i++){
  27.         if(arr[i] == key){
  28.             return i;
  29.         }
  30.     }
  31.     return -1;
  32. }
  33.  
  34. inline Vector::~Vector(){
  35.     delete[] arr;
  36.     arr = NULL;
  37. }
  38.  
  39. inline istream& operator >>(istream &in, Vector &obj){
  40.     for(int i = 0; i < obj.size; i++){
  41.         cout << "arr[" << i << "] = ";
  42.         in >> obj.arr[i];
  43.     }
  44.     cout << endl;
  45.     return in;
  46. }
  47.  
  48. inline ostream& operator <<(ostream &out, Vector &obj){
  49.     for(int i = 0; i < obj.size; i++){
  50.         out << obj.arr[i] << ",";
  51.     }
  52.     return out;
  53. }
  54.  
  55. int main() {
  56.     system("cls");
  57.     cout << "Enter the size of the array: ";
  58.     int size;
  59.     cin >> size;
  60.     Vector obj(size);
  61.     cin >> obj;
  62.     cout << "Enter the element you want to search: ";
  63.     int key;
  64.     cin >> key;
  65.     int pos = obj.search(key);
  66.     if(pos != -1){
  67.         cout << key << " found at " << pos << endl;
  68.     }
  69.     else{
  70.         cout << key << " was not found" << endl;
  71.     }
  72.     cout << "Elements of the array are" << endl;
  73.     cout << obj;
  74.     cin.ignore();
  75.     cin.get();
  76.     return 0;
  77. }
Add Comment
Please, Sign In to add comment