I just need to change the two arrays into two vectors in this function. I need h
ID: 3718904 • Letter: I
Question
I just need to change the two arrays into two vectors in this function. I need help, I don't know the right syntax.
// C++ Code to find Smallest Difference between two Arrays
#include <bits/stdc++.h>
using namespace std;
// function to calculate Small result between two arrays
int findSmallestDifference(int arr1[], int arr2[],
int m, int n)
{
// Sort both arrays using sort function
sort(arr1, arr1+m);
sort(arr2, arr2+n);
int a = 0, b = 0;
// Initialize result as max value
int result = INT_MAX;
// Searching Both Arrays upto sizeof of the Arrays
while (a<m && b<n)
{
if (abs(arr1[a]-arr2[b]) < result)
result = abs(arr1[a]-arr2[b]);
// Move Smaller Value
if (arr1[a] < arr2[b])
a++;
else
b++;
}
return result; // return final smallest result
}
Explanation / Answer
Please find refactored program.
#include <iostream>
#include <vector>
using namespace std;
bool myfunction (int i,int j) { return (i<j); }
// function to calculate Small result between two vectors
int findSmallestDifference(vector<int> arr1, vector<int> arr2,
int m, int n)
{
// Sort both vectors using sort function
std::sort (arr1.begin(), arr1.begin()+m);
std::sort (arr2.begin(), arr2.begin()+n);
int a = 0, b = 0;
// Initialize result as max value
int result = INT_MAX;
// Searching Both Arrays upto sizeof of the Arrays
while (a<m && b<n)
{
if (abs(arr1[a]-arr2[b]) < result)
result = abs(arr1[a]-arr2[b]);
// Move Smaller Value
if (arr1[a] < arr2[b])
a++;
else
b++;
}
return result; // return final smallest result
}