Write a program that uses a structure Vector. This structure stores an array
V of double numbers, size of array n. This structure contains:
i. Function to input n, and all elements of V.
ii. Function to display n, and all elements of V.
iii. Function to reverse the order of elements of V.
iv. Function to return the element that appears most frequently in the
array.
The program declares a variable of Vector, and applies all functions on it.
#include<iostream>
using namespace std;
void SwapDouble(double* x, double* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
struct Vector
{
int n;
double *arr;
Vector() :arr(NULL), n(0) {}
Vector(const Vector& vec)
{
n = vec.n;
arr = new double[n];
for (int i = 0; i < n; i++)
{
arr[i] = vec.arr[i];
}
}
void InputVec()
{
cout << "Please, enter a size of Vector: ";
cin >> n;
arr = new double[n];
for (int i = 0; i < n; i++)
{
cout << "Please, enter a value " << i + 1 << " for Vector: ";
cin >> arr[i];
}
}
void DisplayVec()
{
cout << "\nVector has " << n << " elements:\n";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}
void Sort()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
SwapDouble(&arr[j], &arr[j + 1]);
}
}
}
}
void ReverseVec()
{
for (int i = 0, j = n - 1; i < n / 2; i++, j--)
{
SwapDouble(&arr[i], &arr[j]);
}
}
int MostFreqVec()
{
//Make new temp Vector from current and sort him
Vector vec(*this);
vec.Sort();
int maxCount, currCount, result;
maxCount = currCount = 1;
result = vec.arr[0];
for (int i = 1; i < vec.n; i++)
{
if (vec.arr[i] == vec.arr[i - 1])currCount++;
else
{
if (currCount > maxCount)
{
maxCount = currCount;
result = vec.arr[i - 1];
}
currCount = 1;
}
}
//if last element is most freq
if (currCount > maxCount)
{
result = vec.arr[n - 1];
}
return result;
}
//Destructor to delete arr
~Vector()
{
delete[] arr;
}
};
int main()
{
Vector v;
v.InputVec();
v.DisplayVec();
cout << "\nReverse of Vector";
v.ReverseVec();
v.DisplayVec();
cout<<"\nMost Frequent value is "<<v.MostFreqVec();
v.DisplayVec();
}
Comments
Leave a comment