Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program to create an array dynamically
- using new and freeing it using delete
- */
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- class Vector{
- int *arr, size;
- public:
- Vector(int);
- int search(int);
- ~Vector();
- friend istream& operator >>(istream&, Vector&);
- friend ostream& operator <<(ostream&, Vector&);
- };
- inline Vector::Vector(int size){
- Vector::size = size;
- arr = new int[Vector::size];
- }
- int Vector::search(int key){
- for(int i = 0; i < size; i++){
- if(arr[i] == key){
- return i;
- }
- }
- return -1;
- }
- inline Vector::~Vector(){
- delete[] arr;
- arr = NULL;
- }
- inline istream& operator >>(istream &in, Vector &obj){
- for(int i = 0; i < obj.size; i++){
- cout << "arr[" << i << "] = ";
- in >> obj.arr[i];
- }
- cout << endl;
- return in;
- }
- inline ostream& operator <<(ostream &out, Vector &obj){
- for(int i = 0; i < obj.size; i++){
- out << obj.arr[i] << ",";
- }
- return out;
- }
- int main() {
- system("cls");
- cout << "Enter the size of the array: ";
- int size;
- cin >> size;
- Vector obj(size);
- cin >> obj;
- cout << "Enter the element you want to search: ";
- int key;
- cin >> key;
- int pos = obj.search(key);
- if(pos != -1){
- cout << key << " found at " << pos << endl;
- }
- else{
- cout << key << " was not found" << endl;
- }
- cout << "Elements of the array are" << endl;
- cout << obj;
- cin.ignore();
- cin.get();
- return 0;
- }
Add Comment
Please, Sign In to add comment